Skip to problem
←

Largest BST Subtree

Hard 0 attempts

Find the largest rooted subtree of the given binary tree that is a binary search tree, and return its node count. A subtree includes its root and all descendants; you cannot omit inconvenient nodes.

Use strict BST ordering at every node: every value in its left subtree must be smaller, and every value in its right subtree must be larger. Equal values violate this ordering. A single node is always a valid BST.

Function contract

root is a nonempty binary tree with val, left, and right node properties. Test inputs use level-order arrays with null for missing children.

Output: Return the number of nodes in the largest complete rooted subtree satisfying strict BST ordering.

Example 1

Input
root = [10,5,15,1,8,null,7]
Output
3

Explanation: The subtree rooted at 5 contains [5,1,8] and is a BST of size 3. The subtree rooted at 15 is invalid because its right child is 7.

Example 2

Input
root = [2,1,3]
Output
3
Constraints
  • 1 <= N <= 10^5
  • 1 <= Node.val <= 10^6

Iterative Postorder

Each subtree reports its size, minimum, maximum, and validity. A parent is a BST only if both children are BSTs and their value ranges lie strictly on the correct sides.

javascript
function largestBstInABinaryTree(root) {
  if (!root) return 0;
  const order = [],
    stack = [root];
  while (stack.length) {
    const node = stack.pop();
    order.push(node);
    if (node.left) stack.push(node.left);
    if (node.right) stack.push(node.right);
  }
  const info = new Map(),
    empty = { size: 0, min: Infinity, max: -Infinity, valid: true };
  let best = 0;
  for (let i = order.length - 1; i >= 0; i--) {
    const node = order[i],
      l = info.get(node.left) || empty,
      r = info.get(node.right) || empty;
    if (l.valid && r.valid && node.val > l.max && node.val < r.min) {
      const size = l.size + r.size + 1;
      best = Math.max(best, size);
      info.set(node, {
        size,
        min: Math.min(node.val, l.min),
        max: Math.max(node.val, r.max),
        valid: true,
      });
    } else info.set(node, { valid: false });
  }
  return best;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript