Validate Binary Search Tree
Validate Binary Search Tree is LeetCode 98 (Medium). Given the root of a binary tree, return true if it is a valid BST:
- every node in a node's left subtree is strictly smaller than it;
- every node in its right subtree is strictly larger;
- both subtrees are valid BSTs too.
Equal values are not allowed. Node values cover the whole 32-bit range, so -2³¹ and 2³¹ - 1 can appear.
- The number of nodes in the tree is in the range [1, 10⁴].
- -2³¹ <= Node.val <= 2³¹ - 1
Intuition
A node must be larger than every node on its left and smaller than every node on its right, not just its two children. So a node deep in the tree is limited by all the ancestors above it.
Those limits fit in one allowed range (low, high) passed down from the parent:
- Going left: everything there must stay below the parent, so
highbecomes the parent's value. - Going right: everything there must stay above the parent, so
lowbecomes the parent's value.
The root may be anything, (−∞, ∞). Each node then needs a single check: is its value strictly inside its range?
This problem is the classic case of a node whose legality depends on ancestors it never sees directly; a range passed down the recursion handles every such problem. Checking each parent against its children looks right but misses those deeper limits. The same range idea shows up in Recover BST and in building a BST from preorder.
Approach
Before reading on: in [5,4,6,null,null,3,7], every parent is ordered correctly against its own children. Is it a valid BST? Which ancestor does node 3 break, and what range would have caught it?
Two ways to solve it
Pass an allowed range (low, high) down the tree and check each node against it.
- Check: one comparison per node, no extra state.
- Stops: at the first node outside its range.
- Explains: which ancestor a bad node breaks.
The version most interviewers expect.
Visit nodes in inorder (left, node, right) and check each value is larger than the one before.
- Check: compare with a single
prevvalue. - Stops: at the first value that is not larger.
- Watch:
prevmust survive across calls.
Short, and easy to make iterative.
Both visit each node once and use the same memory; the range check is easier to reason about node by node. The steps, code and live demo follow the range check; the inorder code comes after the demo.
Start the root with no limits
Call valid(root, -inf, inf). Nothing sits above the root, so any value is allowed there. Infinity (or a 64-bit long in C++ and Java) leaves room for node values equal to -2³¹ or 2³¹ - 1.
Check the node against its range
An empty subtree is valid. Otherwise, if node.val is not strictly between low and high, return false straight away. The comparison is strict on both sides because equal values make a BST invalid.
Narrow the range for each child
Recurse into node.left with (low, node.val) and into node.right with (node.val, high). The range keeps every limit from the ancestors, so one check per node is enough. Return true only if both subtrees are valid.
Code in Python, C++ and Java
and stops every call above from checking anything else.and stops every call above from checking anything else.Inorder traversal check
Walk the tree in inorder, which visits a BST's values in sorted order, and keep the last value seen in prev. Any value that is not larger than prev breaks the BST.
Common pitfalls
Comparing each node only with its children
def valid(node):
if not node:
return True
if node.left and node.left.val >= node.val:
return False
if node.right and node.right.val <= node.val:
return False
return valid(node.left) and valid(node.right)def valid(node, low, high):
if not node:
return True
if not (low < node.val < high):
return False
return valid(node.left, low, node.val) and valid(node.right, node.val, high)In [5,4,6,null,null,3,7], node 6 has children 3 and 7, which look fine. But 3 is in the right subtree of 5 and is smaller than 5. Only a range carried down from the root catches it.
Allowing equal values
if not (low <= node.val <= high):
return Falseif not (low < node.val < high):
return FalseLeetCode's BST needs strictly smaller values on the left and strictly larger on the right, so [2,2,2] is not valid. With <=, it passes.
Using int limits as the starting range
return valid(root, Integer.MIN_VALUE, Integer.MAX_VALUE); // int low, high
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE); // long low, high
A tree holding exactly 2147483647 is valid, but node.val < Integer.MAX_VALUE is false, so it gets rejected. In C++ and Java, use long limits (or null for no limit); in Python, float("inf") does the job.
Complexity
Validate Binary Search Tree FAQ
Is it enough to check that the inorder traversal is sorted?
Yes. A tree is a valid BST exactly when its inorder traversal is strictly increasing. You do not need to store the whole list: keep the previous value and compare as you go, as in the second method below.
Can it be done without recursion in Python?
Run an iterative inorder walk with a stack: push left children until you hit None, pop a node, check it is larger than the previous value, then move to its right child. This avoids deep recursion when the tree is a long chain.