Skip to content

285. Inorder Successor in BST 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
    if (root == nullptr)
      return nullptr;
    if (root->val <= p->val)
      return inorderSuccessor(root->right, p);

    TreeNode* left = inorderSuccessor(root->left, p);
    return left ? left : root;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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;
  }
}
1
2
3
4
5
6
7
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