面试题 04.06 找出二叉搜索树中指定节点的“下一个”节点

题目:

 

 

解答:

 

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) 
13     {
14         if (root == NULL || p == NULL) 
15         {
16             return NULL;
17         }
18         if (p->val >= root->val) 
19         {
20             return inorderSuccessor(root->right, p);
21         } 
22         else 
23         {
24             TreeNode* left = inorderSuccessor(root->left, p);
25             return left ? left : root;
26         }
27     }
28 };

 

posted @ 2020-05-09 23:14  梦醒潇湘  阅读(271)  评论(0)    收藏  举报