Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Given

Java
class Node {
int val;
Node left, right;
}

write a method that checks whether a binary tree is a valid binary search tree. Explain why checking only each node against its direct children is wrong.

To validate a binary search tree, we pass down the range each node's value must fall into: valid(node, low, high) checks low < node.val < high and then checks the left child with the range (low, node.val) and the right child with (node.val, high), using long bounds so Integer.MIN_VALUE and Integer.MAX_VALUE work. Checking each node only against its direct children is wrong because the BST rule applies to whole subtrees: 5 with right child 7 whose left child is 3 passes every parent-child check, yet 3 sits on the right of 5. An in-order traversal that must be strictly increasing is an equivalent alternative, and both run in O(n) time and O(h) stack space.

Why this question is asked

Validating a BST is a short coding question with a well-known trap, and interviewers use it to see whether we understand what the BST property really says, not just its one-line summary. It also tests edge cases with integer limits and duplicates, and whether we notice that recursion depth equals tree height. In this answer, we will restate the BST rule precisely, show why the parent-child check fails, write the bounds solution, write the in-order alternative, and discuss complexity, deep trees and duplicates.

1What the BST Rule Really Says

A binary search tree is a binary tree where, for every node, all values in its left subtree are smaller than the node's value and all values in its right subtree are larger. The important word is all. The rule is not about a node's two children; it is about everything below each side.

This is what makes search work. When we look for 3 and the root is 5, we go left and never look at the right subtree again. That shortcut is only correct if no value smaller than 5 hides anywhere on the right.

2Why Checking Only Direct Children Is Wrong

The tempting solution checks that each node's left child is smaller and its right child is larger, recursively. Here is the tree that fools it: 5 at the root, 7 as its right child, and 3 as the left child of 7.

Java
class Node { int val; Node left, right; Node(int v) { val = v; } }
static boolean naive(Node n) {
if (n == null) return true;
if (n.left != null && n.left.val >= n.val) return false;
if (n.right != null && n.right.val <= n.val) return false;
return naive(n.left) && naive(n.right);
}
Node root = new Node(5);
root.right = new Node(7);
root.right.left = new Node(3);
naive(root); // true, but the tree is not a valid BST
Constraints along the path to node 3
NodeComes fromAllowed rangeValueValid?
5root(-inf, +inf)5yes
7right of 5(5, +inf)7yes
3left of 7(5, 7)3no: 3 is not greater than 5
The lower bound 5 is inherited from the grandparent; a parent-only check never sees it.

Every parent-child pair is fine: 7 is greater than 5, and 3 is smaller than 7. But 3 is in the right subtree of 5, so it must be greater than 5, and it is not. A search for 3 would go left from 5 and miss it. The naive check fails because a node must satisfy a constraint from every ancestor, not only from its parent.

3The Fix: Pass Down the Allowed Range

Each node inherits a range from its ancestors. Going left from a node lowers the upper bound to that node's value; going right raises the lower bound to it. So we pass the range down as two parameters and check each node against it.

Java
static boolean isValidBst(Node root) {
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private static boolean valid(Node n, long low, long high) {
if (n == null) return true; // an empty subtree is valid
if (n.val <= low || n.val >= high) return false; // strictly inside the range
return valid(n.left, low, n.val) // left side: below n.val
&& valid(n.right, n.val, high); // right side: above n.val
}
isValidBst(root); // false: 3 is outside (5, 7)
Node single = new Node(Integer.MIN_VALUE);
isValidBst(single); // true, thanks to long bounds

Notice the long bounds. If we used int and started with Integer.MIN_VALUE and Integer.MAX_VALUE as the bounds, a node whose value is exactly Integer.MIN_VALUE would fail the strict check val > low even though it is valid. Using long makes the starting bounds lie outside every possible int. Another common approach uses Integer bounds that may be null, meaning "no bound", which also works for long-valued trees.

4The Alternative: In-Order Traversal Must Increase

An in-order traversal visits the left subtree, then the node, then the right subtree. For a valid BST, that visits the values in sorted order. So we can traverse in order and check that each value is strictly greater than the previous one. Here it is written iteratively, with an explicit stack instead of recursion.

Java
static boolean isValidInOrder(Node root) {
Deque<Node> stack = new ArrayDeque<>();
Node cur = root;
boolean hasPrev = false;
int prev = 0;
while (cur != null || !stack.isEmpty()) {
while (cur != null) { stack.push(cur); cur = cur.left; } // go as far left as possible
cur = stack.pop();
if (hasPrev && cur.val <= prev) return false; // not strictly increasing
prev = cur.val;
hasPrev = true;
cur = cur.right;
}
return true;
}
isValidInOrder(root); // false: the in-order sequence is 5, 3, 7

Notice the hasPrev flag instead of a sentinel like Integer.MIN_VALUE for prev, which would wrongly reject a tree whose smallest value is Integer.MIN_VALUE. This version can also stop at the first violation, and since it uses a heap-allocated stack, very deep trees do not risk StackOverflowError.

5Complexity, Deep Trees and Duplicates

Both solutions visit every node once, so they are O(n) time. Their extra space is O(h), where h is the tree's height: the recursion depth for the bounds version, or the stack size for the in-order version. For a balanced tree, h is about log2(n); for a skewed tree, h can be n. A recursive validator on a 100,000-node tree that is effectively a linked list will overflow the default thread stack, so for untrusted or possibly skewed input the iterative version is safer.

Duplicates need a stated rule, because definitions differ. The code above treats any duplicate as invalid, which is the common interview definition. Some trees allow duplicates on one side, for example all equal values go to the left; then the checks become val <= high on the left and val > low on the right, or in-order becomes non-decreasing for that side. Saying out loud which rule we use is part of a good answer.

6Follow-up questions

Is a tree with one node a valid BST? What about an empty tree?

Both are valid. An empty tree has no node that could break the rule, and a single node has no subtrees, so the rule holds trivially. The code returns true for null at the start and checks the single node only against the infinite bounds.

Why not compare each node with the maximum of its left subtree and the minimum of its right subtree?

That definition is correct, but computing the max and min for each node separately makes it O(n^2) in the worst case. Returning min and max from each recursive call fixes that and gives O(n), but the bounds approach does the same work with less code.

How would you validate a BST stored in an array, such as a heap layout?

The same bounds idea works with indexes: the children of index i are at 2i + 1 and 2i + 2. We traverse indexes with an explicit stack holding the index and its bounds, which avoids building node objects at all.

7Conclusion

In this answer, we saw that the BST rule constrains whole subtrees, so a node must respect bounds inherited from all its ancestors, and checking only direct children misses cases like 5, right child 7, and 7's left child 3. Passing a low and high bound down the recursion, with long bounds to cover the int limits, validates the tree in O(n) time and O(h) space, and an in-order traversal that must be strictly increasing is an equivalent check that can run iteratively for deep, skewed trees. We also saw that duplicates need an explicitly stated rule.

What to say in the interviewAbout 80 seconds aloud

Open with

The BST rule is about whole subtrees: everything on the left of a node is smaller and everything on the right is larger. So comparing a node only with its direct children is wrong.

Then, if they want more

The classic counterexample is 5 with a right child 7, and 7 has a left child 3: each parent and child pair looks fine, but 3 is in the right subtree of 5, and a search for 3 would never find it.

My solution passes the allowed range down: valid of node, low, high returns true for null, returns false if the value is not strictly between low and high, and otherwise checks the left child with low and the node's value, and the right child with the node's value and high.

I use long bounds starting at Long.MIN_VALUE and Long.MAX_VALUE so a node holding Integer.MIN_VALUE or MAX_VALUE is still handled. An equivalent approach is an in-order traversal, which must produce strictly increasing values, keeping only the previous value.

Both are O(n) time and O(h) space, where h is the height, so for a skewed tree I would use the iterative in-order version with an explicit stack to avoid a stack overflow. I would also state the duplicate rule, since here I treat duplicates as invalid.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Given class Node { int val; Node left, right; }, write a method that checks whether a...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/f7df8f614b/