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. Think of it as finding the "next" node that would appear after p in a sorted traversal of the tree.

Key Insight: In a BST, the inorder traversal visits nodes in sorted order. The inorder successor is simply the next node in this sorted sequence.

Example: If we have nodes with values [1, 3, 6, 7, 8, 10, 13] in inorder traversal, then the successor of node 6 is node 7, and the successor of node 13 is null (no larger value exists).

Input & Output

example_1.py โ€” Basic Case with Right Subtree
$ Input: root = [5,3,6,2,4,null,null], p = 3
โ€บ Output: 4
๐Ÿ’ก Note: Node 3 has a right subtree. The inorder successor is the leftmost node in the right subtree, which is node 4.
example_2.py โ€” No Right Subtree
$ Input: root = [5,3,6,2,4,null,null], p = 4
โ€บ Output: 5
๐Ÿ’ก Note: Node 4 has no right subtree. We traverse from root: 4 < 5, so 5 is a potential successor. Going left to 3, then right to 4. The successor is 5.
example_3.py โ€” No Successor (Maximum Node)
$ Input: root = [2,1,3], p = 3
โ€บ Output: null
๐Ÿ’ก Note: Node 3 is the maximum node in the tree, so it has no inorder successor.

Visualization

Tap to expand
Case 1: Has Right SubtreeGo right โ†’ then left as far as possibleCase 2: No Right SubtreeFind deepest ancestor from left turnPโ†’SRight subtree โ†’ Find leftmostPASNo right subtree โ†’ Go up to ancestorTime: O(h), Space: O(1)where h = height of tree
Understanding the Visualization
1
Check Right Shelf
If current book has books to the right, go there and find the leftmost book
2
Go Back to Ancestors
Otherwise, go back up the tree until you find an ancestor you approached from the left
3
Found or None
That ancestor is your successor, or null if you're at the maximum
Key Takeaway
๐ŸŽฏ Key Insight: BST structure allows direct navigation to successor - either find minimum in right subtree, or backtrack to find the first left-turn ancestor.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(h)

In worst case, traverse from root to leaf, where h is height of tree. For balanced BST, h = log(n)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a few pointer variables, no additional data structures needed

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • All Nodes will have unique values
  • p will exist in the BST
Asked in
Microsoft 45 Amazon 38 Google 32 Meta 28
67.2K Views
High Frequency
~18 min Avg. Time
1.8K 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