Given the root of a binary tree, decide whether it is a valid binary search tree (BST).
A BST is valid when, for every node, all values in its entire left subtree are strictly less than the node's value and all values in its entire right subtree are strictly greater. The rule applies to whole subtrees, not just direct children, so a value that is fine relative to its parent can still violate an ancestor's bound.
Example 1
Input: root = [2,1,3]
Output: true
1 < 2 < 3, and each subtree respects the ordering, so the tree is a valid BST.
Example 2
Input: root = [5,1,4,null,null,3,6]
Output: false
The root is 5, but its right subtree contains 3, which is less than 5. That breaks the BST rule, so the answer is false.
Constraints
The number of nodes in the tree is in the range [1, 10^4].-2^31 <= Node.val <= 2^31 - 1See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI