← DiffPush

Largest BST Subtree in a Binary Tree

DiffPush Tier Binary Search Trees · Practice Problems O(n) · O(h)

Mapping the Largest Compliant Zone

A distribution yard was laid out with the sorted smaller-left rule, but some zones drifted out of compliance as stock moved. Inspectors want the biggest fully compliant zone: a subtree where every aisle still honors the ordering rule. Each supervisor reports upward three facts — zone population, its smallest and largest value — so a parent can instantly test whether merging with its children keeps the whole span compliant.

Input: A binary tree as a level-order array (null marks a missing child) — not guaranteed to be a BST.

Output: Return the number of nodes in the largest subtree that is a valid BST.

Constraints

Examples

Example 1

Input: {"tree":[10,5,15,1,8,null,7]}
Output: 3
The subtree rooted at 5 (values 5, 1, 8) is a valid BST; the right wing's 7 spoils the root and 15.

Example 2

Input: {"tree":[1,4,4,6,8]}
Output: 1
Only individual leaves qualify — every internal node violates the ordering rule.

Solve this in your browser →

Also on LeetCode ↗