Validate Binary Search Tree
Check the BST rule for whole subtrees by passing down the range each node's value must fall in.
The problem
You get the root of a binary tree. Return true if it is a valid binary search tree: every value in a node's left subtree is strictly smaller than the node, every value in its right subtree is strictly larger, and both subtrees are valid BSTs too. Equal values are not allowed anywhere.
Input root = [8, 4, 12, 2, 6, 10, 14]
Output true
Every node is larger than everything on its left and smaller than everything on its right.
Input root = [8, 4, 12, 2, 9]
Output false
9 is a fine right child for 4, but it sits in the left subtree of 8, where every value must be smaller than 8.
Key constraint: Node values can be as small as -2^31 and as large as 2^31 - 1, so the starting bounds must lie outside the int range.
How to spot the pattern
- The rule compares a node with all of its ancestors, not only with its parent.
- Each step down the tree narrows the range of values allowed below it.
The idea
Checking each node against its parent is not enough: a node deep in the left subtree must also be smaller than the root. Every ancestor adds a limit, and together the limits form a range (low, high). Going left lowers the upper limit to the current value, going right raises the lower limit, and every node must fall strictly inside its range.
Brute force: For every node, scan its whole left and right subtrees for their largest and smallest values, which takes O(n^2) time on a skewed tree.
Step by step
- 1Start at the root with the range from minus infinity to plus infinity.
- 2If the node is null, return
true. - 3If its value is not strictly between
lowandhigh, returnfalse. - 4Check the left child with the range (
low,node.val) and the right child with the range (node.val,high).
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def valid(node: Optional[TreeNode], low: float, high: float) -> bool:
# Every value in this subtree must be strictly between low and high.
if node is None:
return True
if not (low < node.val < high):
return False
return valid(node.left, low, node.val) and valid(node.right, node.val, high)
return valid(root, float("-inf"), float("inf"))Complexity
Time
O(n)
Space
O(h)
Each node is checked once against two bounds; the recursion stack holds one call per level of the tree.
Watch out for
- Comparing a node only with its own children, which accepts a value in the left subtree that is larger than an ancestor higher up.
- Starting the bounds at
INT_MINandINT_MAX: a node that holds exactly one of those values then fails. Use a wider type or a null bound. - Letting equal values through: a duplicate on either side makes the tree invalid here.
Follow-up questions
Can you solve it with an in-order traversal?
Yes. An in-order walk of a valid BST visits values in strictly increasing order, so remember the previous value and fail as soon as the current one is not larger.
What if equal values were allowed on the left side?
Relax the left check: values on the left must be <= node.val, while values on the right must still be strictly larger.
In Hinglish
Sirf parent se compare karna kaafi nahi, har node ko apne saare ancestors ki di hui range mein hona chahiye. Left jao toh upper limit node ki value ban jaati hai, right jao toh lower limit.