2014-05-03 23:35

题目链接

原题:

For a given node in binary search tree find a next largest number in search tree.

题目:给定一个二叉搜索树的节点,找出此节点在树中的中序后继节点,也就是比它大的最小节点。

解法:右子树向左走到底,左祖先走到顶向右。草稿纸上一画图就清楚了。

代码:

 1 // http://www.careercup.com/question?id=5205167846719488
 2 struct TreeNode {
 3     int val;
 4     TreeNode *left;
 5     TreeNode *right;
 6     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
 7 };
 8 
 9 class Solution {
10 public:
11     int nextLargestNumber(TreeNode *root, int val) {
12         if (root == nullptr) {
13             // nothing to do
14             return val;
15         }
16         
17         left_top = nullptr;
18         return findRecursive(root, val);
19     }
20 private:
21     TreeNode *left_top;
22     
23     int findRecursive(TreeNode *root, int val) {
24         if (root == nullptr) {
25             // not found, return val
26             return val;
27         } else if (root->val > val) {
28             left_top = root;
29             return findRecursive(root->left, val);
30         } else if (root->val < val) {
31             return findRecursive(root->right, val);
32         } else {
33             if (left_top == nullptr) {
34                 // val is the greatest of all.
35                 return val;
36             }
37             if (root->right == nullptr) {
38                 return left_top->val;
39             }
40             
41             left_top = root->right;
42             while (left_top->left != nullptr) {
43                 left_top = left_top->left;
44             }
45             return left_top->val;
46         }
47     };
48 }

 

 posted on 2014-05-03 23:52  zhuli19901106  阅读(149)  评论(0编辑  收藏  举报