Blind 75 · #31 · Trees

Validate Binary Search Tree

MediumBounds recursionTime O(n)Space O(h)

Validate Binary Search Tree is a medium Trees problem from the Blind 75. The key pattern is bounds recursion, and a good solution runs in O(n) time.

Problem

Determine whether a level-order tree is a strict BST: every left value is smaller and every right value is larger.

Examples

Example 1

Input

[8,3,12,1,6,10,14]

Output

true

Example 2

Input

[4,2,6]

Output

true

Example 3

Input

[8,3,10,null,null,7,12]

Output

false

Approach

Pass down the open interval every node must fit in: going left tightens the upper bound, going right the lower bound.

PatternBounds recursion
TimeO(n)
SpaceO(h)

Watch out for

Checking only a node against its children is not enough, and equal values are not allowed.

More Trees problems