p,找到该节点在树中的中序后继。如果节点没有中序后继,请返回 null。
p 的后继是值比 p.val 大的节点中键值最小的节点,即按中序遍历的顺序节点 p 的下一个节点。p,则当前访问节点是 p 的中序后继。root -> val <= p -> val,则结果必定在 root 的右子树中。root 的左子树中或这就是 root。class Solution
{
private:
TreeNode* cur = nullptr;
TreeNode* next = nullptr;
void dfs(TreeNode* root, TreeNode* p)
{
if(!root) return;
dfs(root->left, p);
if(cur)
{
next = next ? next : root;
return;
}
if(root == p) cur = p;
dfs(root->right, p);
return;
}
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p)
{
dfs(root, p);
return next;
}
};
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (!root) return root;
if (root -> val <= p -> val)
return inorderSuccessor(root -> right, p);
auto left = inorderSuccessor(root -> left, p);
return !left ? root : left;
}
};