AlgoInsight

DSA problem

Inorder Successor in BST II

MediumBST / Ordered SetPattern: BST / Ordered Settop600FacebookMicrosoftAmazonGoogleBloomberg

You are given a node node in a binary search tree. Every node in this tree carries an additional parent pointer in addition to the usual left and right children. Return the in-order successor of node without access to the root of the tree.

The catch is that you cannot start a fresh walk from the root because you do not have it. You only have the local view through node.left, node.right, and node.parent. You must derive the successor purely from these references.

There are exactly two cases. Case 1: node has a non-null right child. Then by the BST property, the successor is the leftmost descendant of that right child — keep stepping into .left until you cannot anymore. Case 2: node has no right child. Then the successor lies somewhere up the parent chain. Walk parents until you arrive at a parent for which the previous node was its left child; that parent is the successor. If you walk off the top (parent becomes null), there is no successor and you return null.

This algorithm runs in O(h) time and O(1) space — only two pointers are used. It works on arbitrary BSTs with parent pointers and never needs the root.

Examples

Example 1
Input: tree = [2,1,3], node = 1
Output: 2
Explanation: Node 1 has no right child, so walk up to its parent 2. Since 1 is the left child of 2, the parent is the successor.
Example 2
Input: tree = [5,3,6,2,4,null,null,1], node = 6
Output: null
Explanation: Node 6 has no right child. Walking up, 6 is the right child of 5, so we keep going. 5 has no parent (root), so there is no successor.
Example 3
Input: tree = [5,3,6,2,4,null,null,1], node = 4
Output: 5
Explanation: Node 4 has no right child. Walking up, 4 is the right child of 3 (keep going), then 3 is the left child of 5, so 5 is the successor.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttreeparent-pointeriterative

Browse all DSA problems