Validate Binary Search Tree
1 approach, code in every language
Problem description
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 - 1
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Archive Index Order is our own problem on the technique behind Validate Binary Search Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free