Predecessor and Successor

medium

Given the root of a binary search tree and an integer key, find the predecessor and successor of key in the BST and return them as a two-element array [predecessor, successor].

  • The predecessor is the largest value that is strictly less than key.
  • The successor is the smallest value that is strictly greater than key.

If either does not exist, use -1 in its place. The key may or may not be present in the tree. The tree is given in level-order (breadth-first), using null for missing children.

Hints

You don't need to sort the whole tree — use the BST ordering.
Walk down: a node below the key is a predecessor candidate (go right); above is a successor candidate (go left).
If you land on the key, its predecessor is the rightmost node of the left subtree and its successor the leftmost of the right.

Common doubts

The two-descent still works: it converges on the largest value below the key and the smallest above it.
The minimum of the tree has no predecessor and the maximum has no successor; -1 signals 'none'.
Only if you already have the inorder array; otherwise the descent is faster and uses O(1) space.

Interview follow-ups

Augment nodes with subtree sizes, or repeatedly take the inorder predecessor k times.
Define strict vs non-strict neighbours explicitly; duplicates would need a tie-breaking rule.

Fun facts

  • The predecessor/successor descent is the same skeleton as searching for a key — you just keep the last turn each way.
  • In a balanced BST this is O(log n); in a skewed one it degrades to O(n), like all BST walks.

Asked at

AmazonMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 6
Output: [4, 8]
The largest value below 6 is 4; the smallest above 6 is 8.
Example 2
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 2
Output: [-1, 4]
2 is the minimum, so there is no predecessor; the successor is 4.
Constraints

- The number of nodes is in the range [1, 10^4] - 1 <= Node.val <= 10^5 - All Node.val are unique - 1 <= key <= 10^5

Solve this problem →