Inorder Successor in BST

Walk the BST; whenever current value exceeds p, record it as a candidate and descend left.

Medium
Time O(h) Space O(1)
LeetCode
2 min read
tree bst

Problem#

Given the root of a BST and a node p, return the in-order successor of p (the node with the smallest value greater than p.val), or null if none.

Examples#

  • For BST [2,1,3], p = 12.
  • For BST [5,3,6,2,4,null,null,1], p = 6null.

Constraints#

  • The number of nodes is in [1, 10^4]. All values unique.

Approach#

Walk down the BST. If a node’s value exceeds p->val, this is a potential successor; remember it and go left to find smaller candidates. Otherwise go right.

Solution#

Inorder Successor in BST
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* succ = nullptr;
while (root) {
if (root->val > p->val) {
succ = root;
root = root->left;
} else {
root = root->right;
}
}
return succ;
}
};

Editorial#

The successor is the smallest value greater than p. Going left after recording a candidate refines toward smaller-greater values; going right when node <= p skips entire smaller subtrees. The loop runs in O(h) without ever needing parent pointers.

Complexity#

  • Time: O(h).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.