题目描述
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:
输入: root = [2,1,3], p = 1
2
/ \
1 3
输出: 2
示例 2:
输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/ \
3 6
/ \
2 4
/
1
输出: null
通过次数47,425
提交次数76,411
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/successor-lcci
方法一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int f=0;
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(root==NULL) return NULL;
TreeNode* t=inorderSuccessor(root->left,p);
if(t) return t;
if(f==1) return root;
if(root->val==p->val){
f=1;
}
TreeNode* q=inorderSuccessor(root->right,p);
if(q) return q;
return NULL;
}
};