Leetcode

Inorder Successor in BST

  • Time:O(n)
  • Space:O(h)

C++

class Solution {
 public:
  TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
    if (!root)
      return nullptr;
    if (root->val <= p->val)
      return inorderSuccessor(root->right, p);

    TreeNode* left = inorderSuccessor(root->left, p);
    return left ? left : root;
  }
};

JAVA

class Solution {
  public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    if (root == null)
      return null;
    if (root.val <= p.val)
      return inorderSuccessor(root.right, p);

    TreeNode left = inorderSuccessor(root.left, p);
    return left == null ? root : left;
  }
}

Python

class Solution:
  def inorderSuccessor(self, root: Optional[TreeNode], p: Optional[TreeNode]) -> Optional[TreeNode]:
    if not root:
      return None
    if root.val <= p.val:
      return self.inorderSuccessor(root.right, p)
    return self.inorderSuccessor(root.left, p) or root