Skip to problem
←

BST Predecessor and Successor

Easy 0 attempts

Given a binary search tree root and an integer key, return [predecessorNode, successorNode]:

  • The predecessor is the original node with the largest value strictly less than key.
  • The successor is the original node with the smallest value strictly greater than key.

Use null for either missing neighbor. The key does not need to occur in the tree. If it does occur, that node cannot be its own predecessor or successor. Return node references, not numbers or new nodes, and leave the tree unchanged.

For the first example, 65 is absent but lies between 60 and 70, so those nodes are returned. The editor displays their values as [60, 70].

Input examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement findPreSuc(root, key). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the result described in the statement. Return [predecessorNode, successorNode]; the editor displays their values or null.

Example 1

Input
root = [50,30,70,20,40,60,80]
key = 65
Output
[60,70]

Example 2

Input
root = [1]
key = 1
Output
[null,null]
Constraints
  • 1 <= number of nodes <= 10^4
  • 1 <= Node.val, key <= 10^6
  • All node values are distinct, and the tree satisfies strict BST ordering.

Two BST Searches

For the predecessor, keep the best smaller node seen so far. If the current value is less than key, save it and move right to seek a larger qualifying value. Otherwise move left, since the current node and its right subtree cannot qualify.

Search independently for the successor with the comparisons reversed: save a value greater than key and move left to seek a smaller qualifying value; otherwise move right.

Both searches work whether or not the key exists. Candidates begin as null and remain so when no qualifying node exists. The searches only read the tree and return the original candidate nodes.

javascript
function findPreSuc(root, key) {
  let pre = null,
    suc = null,
    curr = root;
  while (curr) {
    if (curr.val < key) {
      pre = curr;
      curr = curr.right;
    } else curr = curr.left;
  }
  curr = root;
  while (curr) {
    if (curr.val > key) {
      suc = curr;
      curr = curr.left;
    } else curr = curr.right;
  }
  return [pre, suc];
}

Time: O(h) | Space: O(1), where h is tree height. A balanced tree has logarithmic height, but a one-sided tree can have height n.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript