AlgoInsight

DSA problem

Inorder Successor in BST

MediumBST / Ordered SetPattern: BST / Ordered Settop600FacebookAmazonMicrosoftAppleGoogle

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

The in-order successor of a node p is the node with the smallest value greater than p.val. In an in-order traversal of a BST (which produces values in sorted order), the successor is simply the node that comes immediately after p.

A clean but unnecessarily expensive solution performs a full in-order traversal, collects the nodes into a list, finds p in the list, and returns the next entry. That takes O(n) time and space.

The optimal approach exploits the BST ordering directly, without needing access to parent pointers. Walk from the root: whenever node.val > p.val, this node could be the successor — record it as the current candidate and descend left to find an even smaller value above p.val. Whenever node.val <= p.val, descend right because everything in the left subtree is too small. When you fall off the tree, the most recently recorded candidate is the answer, or null if no candidate was ever set. This runs in O(h) time and O(1) extra space.

Examples

Example 1
Input: root = [2,1,3], p = 1
Output: 2
Explanation: The in-order traversal is [1, 2, 3]; the successor of 1 is 2.
Example 2
Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: The in-order traversal is [1, 2, 3, 4, 5, 6]; node 6 is the last in order, so it has no successor.
Example 3
Input: root = [5,3,6,2,4,null,null,1], p = 4
Output: 5
Explanation: The in-order traversal is [1, 2, 3, 4, 5, 6]; the successor of 4 is 5.

Constraints

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

bsttreeiterativebinary-search-tree

Browse all DSA problems