Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Validate a BST

Check whether a binary tree is a valid Binary Search Tree (BST).

Python practice14 minTrees & Binary TreesIntermediateLast updated March 29, 2026

Problem statement

Given the root of a binary tree, determine if 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 contains only nodes with keys strictly greater than the node's key, and both left and right subtrees must also be binary search trees. Return True if the tree is a valid BST, otherwise return False.

Task

Implement an algorithm to verify that a binary tree satisfies BST ordering: left < node < right for every node.

Examples

Simple valid BST

Input

TreeNode(2, TreeNode(1), TreeNode(3))

Output

True

Left child 1 < 2 and right child 3 > 2; both subtrees are valid.

Input format

A single binary tree root (TreeNode or None).

Output format

Boolean value: True if the tree is a valid BST, otherwise False.

Constraints

The number of nodes is in the range [0, 10^4]. Node values are integers and may be negative. Use O(n) time and O(h) auxiliary space where h is the tree height.

Samples

Sample 1

Input

TreeNode(5, TreeNode(1), TreeNode(4, TreeNode(3), TreeNode(6)))

Output

False

The right subtree has a node with value 3 which is not greater than 5.