Largest BST

medium

Given the root of a binary tree (not necessarily a BST), return the number of nodes in the largest subtree that is itself a valid binary search tree. A subtree must include a node and all of its descendants. For a BST here, every left descendant is strictly less and every right descendant strictly greater than the node.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Every leaf is a BST of size 1 — the answer is at least 1 for a non-empty tree.
Top-down BST checks re-scan the same nodes repeatedly; work bottom-up instead.
Have each node return whether its subtree is a BST, plus its size, min, and max.

Common doubts

A node only needs its children's summaries (isBST, size, min, max) to decide in O(1), so no subtree is scanned more than once.
min = +infinity, max = -infinity, so that a leaf's check lmax < val < rmin always passes.
This variant defines a BST with all left descendants strictly less and right strictly greater; equal values would violate it.

Interview follow-ups

Carry the node alongside the size in the summary and update it whenever best changes.
Track (max - min) of valid BST subtrees instead of the node count.

Fun facts

  • This is LeetCode 333 — a classic 'return a tuple from postorder' problem, like height-balanced and diameter.
  • The min/max sentinels for the empty subtree are the crux; getting them backwards silently breaks leaves.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [10, 5, 15, 1, 8, null, 7]
Output: 3
The subtree [5, 1, 8] is a BST with 3 nodes; the tree as a whole is not (7 < 15 on the right).
Example 2
Input: root = [2, 1, 3]
Output: 3
The entire tree is already a BST.
Constraints

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

Solve this problem →