AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Validate Binary Search Tree

The key idea

A node is not just greater than its parent or smaller than it. Every node must fall inside a range fixed by all of its ancestors. Pass a low and high bound down the tree, or do an in-order walk and check the values come out strictly increasing.

Problem

Given the root of a binary tree, decide whether it is a valid binary search tree (BST).

A valid BST is defined as follows: the left subtree of a node contains only nodes with keys strictly less than the node's key, the right subtree of a node contains only nodes with keys strictly greater than the node's key, and both the left and right subtrees must themselves also be valid binary search trees.

Return true if the tree is a valid BST, and false otherwise.

Constraints

Examples

Input: root = [2,1,3] Output: true
Input: root = [5,1,4,null,null,3,6] Output: false

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems