Full answer
Problem
Given the root of a binary tree, return whether it is a valid binary search tree. Every value in the left subtree must be strictly less than the node, and every value in the right subtree strictly greater. Duplicates make the tree invalid in this version.
Example: 5 -> (3 -> 2, 4), (8 -> 7, 9) is valid. 5 -> 3, (8 -> 4, 9) is invalid, because 4 sits in the right subtree of 5.
Constraints: up to 10^4 nodes, values fit in a 64-bit integer.
Brute force
For every node, scan its whole left subtree for the maximum and its whole right subtree for the minimum, and compare. That is O(n^2) on a chain.
A tempting shortcut is to compare each node only with its two children. It is wrong: in the invalid example above, 4 < 8 so the local check passes, but 4 < 5 breaks the rule for the root.
Optimal approach
Recurse with bounds (low, high), starting with (-inf, inf). A node is valid if low < val < high; recurse left with (low, val) and right with (val, high).
Alternative: iterative inorder traversal, tracking the previous value; fail if any value is not greater than the previous one.
Why it works
The BST property says every node must lie between its nearest ancestor where the path turned right (lower bound) and its nearest ancestor where the path turned left (upper bound). Passing bounds down carries exactly those two values. For the inorder version, a binary tree is a BST exactly when its inorder sequence is strictly increasing.
Complexity
O(n) time, each node checked once. O(h) space for recursion or the stack.
Code
import random
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_valid_bst(root, low=float("-inf"), high=float("inf")):
"""Every node must lie strictly inside the (low, high) range set by its ancestors."""
if root is None:
return True
if not low < root.val < high:
return False
return is_valid_bst(root.left, low, root.val) and is_valid_bst(root.right, root.val, high)
def is_valid_bst_inorder(root):
"""Inorder traversal of a BST is strictly increasing. Iterative, O(n) time, O(h) space."""
prev, stack, node = None, [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if prev is not None and node.val <= prev:
return False
prev = node.val
node = node.right
return True
def wrong_local_check(root):
"""Common mistake: only compare each node with its direct children."""
if root is None:
return True
if root.left and root.left.val >= root.val:
return False
if root.right and root.right.val <= root.val:
return False
return wrong_local_check(root.left) and wrong_local_check(root.right)
def brute(root):
vals = []
def walk(n):
if n:
walk(n.left)
vals.append(n.val)
walk(n.right)
walk(root)
return all(a < b for a, b in zip(vals, vals[1:]))
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.25:
return None
return TreeNode(rng.randint(0, 9), random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
good = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(8, TreeNode(7), TreeNode(9)))
trap = TreeNode(5, TreeNode(3), TreeNode(8, TreeNode(4), TreeNode(9))) # 4 is right of 5
dup = TreeNode(2, TreeNode(2))
for f in (is_valid_bst, is_valid_bst_inorder):
assert f(good) and not f(trap) and not f(dup) and f(None) and f(TreeNode(1))
assert wrong_local_check(trap) # the local check is fooled
rng = random.Random(51)
for _ in range(3000):
t = random_tree(rng, 4)
assert is_valid_bst(t) == is_valid_bst_inorder(t) == brute(t)
print("all tests passed")Save as b53_valid_bst.py and run python3 b53_valid_bst.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty tree is valid. Single node. Duplicates (invalid here; some definitions allow them on one side, so ask). Values equal to the integer limits: using -inf and inf (or None bounds) avoids sentinel bugs that appear when a language uses INT_MIN as the sentinel.
Pattern
Top-down state passing: carry constraints from ancestors into the recursion. The same approach handles "is this a valid heap", range-limited tree queries, and path-dependent checks.
import random
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_valid_bst(root, low=float("-inf"), high=float("inf")):
"""Every node must lie strictly inside the (low, high) range set by its ancestors."""
if root is None:
return True
if not low < root.val < high:
return False
return is_valid_bst(root.left, low, root.val) and is_valid_bst(root.right, root.val, high)
def is_valid_bst_inorder(root):
"""Inorder traversal of a BST is strictly increasing. Iterative, O(n) time, O(h) space."""
prev, stack, node = None, [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if prev is not None and node.val <= prev:
return False
prev = node.val
node = node.right
return True
def wrong_local_check(root):
"""Common mistake: only compare each node with its direct children."""
if root is None:
return True
if root.left and root.left.val >= root.val:
return False
if root.right and root.right.val <= root.val:
return False
return wrong_local_check(root.left) and wrong_local_check(root.right)
def brute(root):
vals = []
def walk(n):
if n:
walk(n.left)
vals.append(n.val)
walk(n.right)
walk(root)
return all(a < b for a, b in zip(vals, vals[1:]))
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.25:
return None
return TreeNode(rng.randint(0, 9), random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
good = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(8, TreeNode(7), TreeNode(9)))
trap = TreeNode(5, TreeNode(3), TreeNode(8, TreeNode(4), TreeNode(9))) # 4 is right of 5
dup = TreeNode(2, TreeNode(2))
for f in (is_valid_bst, is_valid_bst_inorder):
assert f(good) and not f(trap) and not f(dup) and f(None) and f(TreeNode(1))
assert wrong_local_check(trap) # the local check is fooled
rng = random.Random(51)
for _ in range(3000):
t = random_tree(rng, 4)
assert is_valid_bst(t) == is_valid_bst_inorder(t) == brute(t)
print("all tests passed")Bounds recursion, iterative inorder, the wrong local check (shown failing), and a random cross-check against sorted-inorder.
Complexity
Time: O(n). Space: O(h). Inorder can stop at the first violation, so invalid trees often finish early.
By level
Fresher: Writes the bounds recursion and explains with a counterexample why checking only children fails. Knows that inorder output of a BST is sorted.
Mid: Implements the iterative inorder check with one previous value and discusses sentinel pitfalls. Handles a duplicates policy given by the interviewer.
Senior: Extends to recovering a BST with two swapped nodes using the inorder inversion pattern. Discusses validating very large or persisted trees in a streaming way, checking each node once with bounded memory.
Key points
- Every node must satisfy bounds from all ancestors, not just its parent
- Pass (low, high) down the recursion
- Inorder of a BST is strictly increasing
- Use infinities or None for bounds, not integer sentinels
- O(n) time, O(h) space
Common mistakes
- Comparing only with direct children
- Using <= and allowing duplicates without asking
- Using INT_MIN/INT_MAX as sentinels when node values can equal them
- Storing the whole inorder list when one previous value is enough
Follow-ups
- How would you recover a BST where exactly two nodes were swapped?
- How do you allow duplicates on the left side only?
- How would you validate a BST stored in an array?
Tips
- Show the counterexample that breaks the local check
- Ask how duplicates are treated
- Offer both the bounds and the inorder method
Evaluation rubric
- Correct global constraint
- Correct handling of duplicates and limits
- O(n) time
- Explains the counterexample