Inorder Successor in BST - Problem

Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST.

If the given node has no in-order successor in the tree, return null.

The successor of a node p is the node with the smallest key greater than p.val.

Input & Output

Example 1 — Node with Right Subtree
$ Input: root = [2,1,3], p = 1
Output: 2
💡 Note: Node 1 has no right child, so we look for the ancestor where 1 is in the left subtree. Starting from root 2, since 1 < 2, node 2 is the successor of 1.
Example 2 — Node without Right Subtree
$ Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
💡 Note: Node 6 has no right child and is the largest node in the BST, so it has no inorder successor. Return null.
Example 3 — Leftmost in Right Subtree
$ Input: root = [5,3,6,2,4], p = 3
Output: 4
💡 Note: Node 3 has a right child. The successor is the leftmost node in the right subtree of 3, which is node 4.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 ≤ Node.val ≤ 105
  • All Node.val are unique
  • p is a TreeNode in the tree

Visualization

Tap to expand
Inorder Successor in BST INPUT Binary Search Tree 2 1 p (target) 3 root = [2, 1, 3] p = 1 Find successor of node 1 (smallest key greater than 1) ALGORITHM STEPS 1 Start at Root Initialize successor = null 2 Compare p.val 1 < 2, so update successor=2 3 Go Left Move to left subtree 4 Found p No right child, return succ BST Property If p.val < curr.val: curr could be successor If p.val >= curr.val: go right for larger value FINAL RESULT Successor Found 2 SUCCESSOR 1 p 3 Output: 2 OK - Smallest > 1 Key Insight: BST Property Optimization: When searching for successor, if p.val < current, current is a candidate. Move left to find smaller candidates. If p.val >= current, move right. Time: O(h), Space: O(1). TutorialsPoint - Inorder Successor in BST | BST Property Optimization Approach
Asked in
Amazon 15 Facebook 12 Microsoft 10 Google 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen