Skip to problem
←

BST with a Dead End

Easy 0 attempts

Given a binary search tree of distinct positive integers, determine whether it contains a dead end: a leaf below which no new distinct positive integer can be inserted while preserving the BST ordering.

The allowed values below a leaf are bounded by its ancestors and by the minimum value 1. For example, in a tree with root 2 and left child 1, the leaf 1 is a dead end: nothing lies below 1, and no integer lies strictly between 1 and 2.

Function contract

Implement isDeadEnd(root). The runner converts the level-order array into nodes with val, left, and right fields. The BST contains distinct positive integers.

Output: true if some leaf cannot accept any new distinct positive integer anywhere beneath it while preserving the BST ordering; otherwise false.

Example 1

Input
root = [8,5,11,2,7,null,null,1,3]
Output
true

Example 2

Input
root = [8,5,11]
Output
false
Constraints
  • 1 <= N <= 10^4
  • 1 <= Node.val <= 10^4
  • All node values are distinct; the input is a valid BST.

Iterative Range Tracking

Each node has an inclusive range of allowed positive integers. When the lower and upper bounds are equal, no further value can be inserted below that node.

javascript
function isDeadEnd(root) {
  const stack = root ? [[root, 1, Infinity]] : [];
  while (stack.length) {
    const [node, lo, hi] = stack.pop();
    if (lo === hi) return true;
    if (node.left) stack.push([node.left, lo, node.val - 1]);
    if (node.right) stack.push([node.right, node.val + 1, hi]);
  }
  return false;
}

Time: O(n) | Space: O(h) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript