Inorder Successor in BST II - Problem

Given a node in a binary search tree, return the in-order successor of that node in the BST. If that node has no in-order successor, return null.

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

You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node.

The definition for Node is:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

Input & Output

Example 1 — Node with Right Subtree
$ Input: node = Node(3) in BST [2,3,4,5,6,7,8]
Output: Node(5)
💡 Note: Node 3 has a right subtree starting with 5. The leftmost node in this right subtree is 5, so the successor is 5.
Example 2 — Node without Right Subtree
$ Input: node = Node(4) in BST [2,3,4,5,6,7,8]
Output: Node(5)
💡 Note: Node 4 has no right subtree. We go up to parent 3, then to parent 5. Since 4→3→5 and we came from the left at 5, the successor is 5.
Example 3 — Rightmost Node
$ Input: node = Node(8) in BST [2,3,4,5,6,7,8]
Output: null
💡 Note: Node 8 is the rightmost node in the BST, so it has no inorder successor. Return null.

Constraints

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

Visualization

Tap to expand
Inorder Successor in BST II INPUT BST Structure: 5 3 INPUT NODE 7 2 4 6 8 Each node has parent pointer node = Node(3) BST: [2,3,4,5,6,7,8] Inorder: 2,3,4,5,6,7,8 Successor of 3 is 4 Wait - node 3 has right child! ALGORITHM STEPS 1 Check Right Subtree If node has right child, go right, then leftmost 2 Node 3 has right=4 Go to right child (4) 4 has no left child 3 Alternative Case If no right child: go up until coming from left 4 Return Result Successor found = 4 Path Visualization: 3 4 right child = successor FINAL RESULT Successor Found: 4 Node(4) Output: Node(4) Why Node 4? - Inorder: 2,3,4,5,6,7,8 - After 3 comes 4 - 4 is smallest value greater than 3 - Status: OK Key Insight: Two cases for finding inorder successor using parent pointers: 1) If right subtree exists: Go right once, then keep going left until null (leftmost node) 2) If no right subtree: Traverse up using parent until we find ancestor from its left child. Time: O(h) TutorialsPoint - Inorder Successor in BST II | BST Property Utilization Approach
Asked in
Google 25 Facebook 20 Microsoft 18 Amazon 15
98.3K Views
Medium Frequency
~15 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