在二叉搜索树中找最小的大于某个key值的节点
如
8
/ \
6 12
/ / \
2 11 14
key = 8 返回11
key = 1 返回2
key = 16 返回NULL
struct TreeNode { int val; TreeNode* left; TreeNode* right; }; // 迭代实现 TreeNode * FindCeiling(TreeNode *root, int key) { TreeNode * ceiling = NULL; TreeNode * current = root; while(current) { if(current->val > key) current = current->left; else { ceiling = current; current = current->right; } } return ceiling; } // 递归实现 TreeNode * FindCeiling(TreeNode *root, int key) { if(root == NULL) return NULL; if(root->val <= key) return FindCeiling(root->right, key); else { TreeNode *ceiling = FindCeiling(root->left, key); return ceiling ? ceiling : root; } }