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 BST213p = 1successorInorder: 1 → 2 → 3123Successor of 1 is 2
Understanding the Visualization
1
Input
BST and target node p
2
Process
Use BST properties to find successor
3
Output
Next node in inorder sequence
Key Takeaway
🎯 Key Insight: BST structure allows us to find successors in O(h) time by following specific paths rather than visiting all nodes
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