Successor
Standard · Write code · about 10 min
Given the root of a BST and a number x, return the smallest key in the tree that is bigger than x. Return -1 if no key is bigger. x does not have to be in the tree.
Example 1
Input:
[[2,1,3],1]
Output:
2
2 is the next key after 1.
Example 2
Input:
[[5,3,6,2,4,null,null,1],6]
Output:
-1
6 is the largest key, so there is no successor.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- Keys are distinct integers with 0 ≤ key ≤ 1,000
- 0 ≤ x ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: BST delete; successor and predecessor, a visual lesson.
More BST delete; successor and predecessor problems
- Pick the tree after a delete Warm-up
- Delete a node with two children Standard
- Implement delete Standard
- Spot the bug: lost subtree Standard
- Delete with the predecessor instead Challenge