Skip to content
BytePatterns

Largest BST Inside a Tree

MediumTrees & BST#post-order#bst~30m

Problem

A binary tree holds whole-number keys, and keys may repeat. A subtree means a node together with all of its descendants. Return the number of nodes in the largest subtree that is a valid binary search tree, where every key in a node's left subtree is strictly smaller than the node and every key in its right subtree is strictly larger. An empty tree has answer 0.

Examples

Input:  tree = 6, left 4 (children 2 and 5, and 2 has a left child 1),
        right 9 (children 7 and 3)
Output: 4
Why:    the subtree under 4 holds 1, 2, 4, 5 in order; 3 under 9 spoils the rest
Input:  tree = 5, left 3, right 8 (children 7 and 9)
Output: 5
Why:    the whole tree is already a valid search tree
Input:  tree = empty
Output: 0
Why:    edge case, no nodes at all

Hints

0 / 3

Stuck on the idea rather than the code? Validate a BST covers it.