Validate Binary Search Tree solution explained
To validate a binary search tree, check every node against the range its ancestors allow, not only against its own children. Pass a lower and an upper bound down the tree: a left child inherits the parent's value as its new upper bound, a right child inherits it as its new lower bound, and any value outside its range means the tree is invalid. An equivalent check is that an in-order walk produces strictly increasing values. Both run in O(n).
By Evin JohnPublished 7 min read
The rule to check
A binary search tree requires, at every node, that all values in its left subtree are smaller than the node's value and all values in its right subtree are larger. Given a binary tree, return true if it follows that rule everywhere. In the usual version duplicates are not allowed, so equal values make the tree invalid. An empty tree is valid.
8 8
/ \ / \
4 12 4 12
/ \ / \ / \
6 15 2 6 10 15
not valid validIn the left tree, 6 is smaller than its parent 12, so a local check passes. But 6 sits in the right subtree of 8, where every value must be larger than 8. A single node is valid, and so is any tree whose in-order listing strictly rises. Ask about duplicates up front: some versions allow equal values on one side, and that changes one comparison.
Why interviewers like it
The problem has a famous trap, which makes it a good test of whether you think about the whole rule or just the nearest case. Many candidates write the parent-child comparison, test it on a small tree where it happens to work, and move on. The interviewer then offers the left tree above. Showing the trap yourself before coding is the strongest start. The search tree property also powers other problems, such as the walk-down shortcut in Lowest Common Ancestor.
Slow but correct: compare with every descendant
At each node, gather every value in its left subtree and check they are all smaller, gather every value in its right subtree and check they are all larger, then recurse into both children. It follows the definition literally. Gathering subtree values at every node costs O(n) per node in the worst case, so the total is O(n²) on a chain-shaped tree.
def values(node):
if node is None:
return []
return values(node.left) + [node.val] + values(node.right)
def is_search_tree_slow(node):
if node is None:
return True
if any(v >= node.val for v in values(node.left)):
return False
if any(v <= node.val for v in values(node.right)):
return False
return is_search_tree_slow(node.left) and is_search_tree_slow(node.right)Pass the allowed range down
Every node in a valid search tree lives inside an open interval set by its ancestors. The root may hold anything. Going left from a node tightens the upper bound to that node's value; going right tightens the lower bound. So carry the pair (low, high) down with each node and check the node's value against it. A value equal to a bound fails, since duplicates are not allowed. Using None for a missing bound, rather than a large number like infinity or the language's maximum integer, keeps the code correct for any value, including the extreme ones.
def is_search_tree(root):
stack = [(root, None, None)] # node, exclusive lower bound, exclusive upper bound
while stack:
node, low, high = stack.pop()
if node is None:
continue
if (low is not None and node.val <= low) or (high is not None and node.val >= high):
return False
stack.append((node.left, low, node.val))
stack.append((node.right, node.val, high))
return TrueTrace the invalid tree. The root 8 gets no bounds and passes. 12 gets (8, none), passes. 6, as 12's left child, gets (8, 12), and 6 is not greater than 8, so the function returns false. A plain parent-child check never compares 6 with 8.
The in-order alternative
An in-order traversal visits the left subtree, then the node, then the right subtree. In a valid search tree that visits values in sorted order. So walk the tree in order and check that each value is strictly greater than the one before it. You only need to remember the previous value, not the whole listing. The iterative form below uses a stack to go as far left as possible, visit, then turn right.
function isSearchTree(root) {
// In-order traversal must produce strictly increasing values.
const stack = [];
let node = root;
let previous = null;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
if (previous !== null && node.val <= previous) return false;
previous = node.val;
node = node.right;
}
return true;
}Complexity
| Approach | Time | Extra space |
|---|---|---|
| Compare with every descendant | O(n²) worst case | O(n) for gathered values |
| Parent-child comparison only | O(n) | O(h), but wrong |
| Bounds passed down | O(n) | O(h) |
| In-order walk with previous value | O(n) | O(h) |
| Morris in-order traversal | O(n) | O(1), temporarily rewires links |
Cases to test
- Empty tree and single node: valid.
- A grandchild that violates an ancestor's bound, like the left drawing.
- Duplicate values, such as a node with a left child of equal value: invalid in the usual version.
- Values at the extremes of the integer range, which break sentinel bounds like the maximum integer.
- A valid tree with two values swapped, which should fail.
Frequent errors
- Comparing only with the direct children.
- Using less than or equal where the problem forbids duplicates, or the reverse.
- Starting bounds at the language's minimum and maximum integers, which wrongly rejects a node holding exactly that value.
- In the in-order version, starting the previous value at 0 or at a minimum constant instead of "none yet".
- Building the full in-order list and checking it is sorted, then describing that as O(1) extra space.
Follow-ups
- Two nodes were swapped by mistake; fix the tree. An in-order walk finds the one or two places where the order drops; swap those values back.
- Allow duplicates on the left. Change one comparison: a left child may equal its upper bound.
- Find the largest valid search tree inside a tree. Return min, max, size and validity from each subtree bottom-up.
- The k-th smallest value. Run the same in-order walk and stop at the k-th visit.
Talking it through
Fictional example
- Candidate
- Checking each node against its children isn't enough. If I put 6 under the 12 on the right side of an 8, every pair looks fine but the tree is invalid.
- Candidate
- So I'll pass an allowed range down. Going left sets the upper bound to the parent's value, going right sets the lower bound. A value that touches or crosses a bound fails.
- Candidate
- That's linear time and stack depth equal to the height. I use None for an open bound so extreme values don't break it.
Related walkthroughs
Count Good Nodes in Binary Tree passes one value down instead of two bounds. Balanced Binary Tree checks a different rule at every node, and Subtree of Another Tree compares whole subtrees. The coding problems hub lists every pattern.
Practice support from Natively
When you rehearse on a Mac or Windows machine, Natively can read the search tree prompt from a screenshot and point out the grandchild trap before you code, or compare the bounds and in-order approaches. A transcript of the mock session is kept with your notes, so you can check whether you raised the duplicates question. The AI interview assistant page explains how practice works.
Questions people ask
How do you validate a binary search tree?
Pass an allowed range down the tree. A left child's upper bound becomes its parent's value and a right child's lower bound becomes its parent's value. If any value falls on or outside its range, the tree is invalid. This is O(n).
Why is comparing a node with its children not enough?
A node can satisfy its parent but break a rule set higher up. For example, a 6 placed as the left child of 12 inside the right subtree of 8 looks fine locally but is smaller than 8.
Can I validate a BST with an in-order traversal?
Yes. An in-order walk of a valid search tree produces strictly increasing values, so check each value against the previous one and fail on the first that does not rise.
How should duplicates be handled in Validate Binary Search Tree?
In the usual version duplicates are not allowed, so equal values make the tree invalid. Some versions allow equal values on one side; ask, then adjust one comparison.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
