Largest BST Subtree

Given the root of a binary tree, return the size of the largest subtree that is itself a valid binary search tree. Pattern focus: BST Validation with Bounds. Each subtree should report its minimum value, maximum value, size, and whether it is valid so the parent can decide efficiently.

Input Format

root = binary tree root

Output Format

size of the largest BST subtree

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node values <= 10^9
  • root must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

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

Output:

3

Explanation:

The subtree rooted at 5 with nodes [5,1,8] is the largest BST.

Example 2:

Input:

root = [4,2,7,1,3,6,9]

Output:

7

Explanation:

The entire tree is a valid BST.

Loading...
Largest BST Subtree - Binary Search Tree