Validate a BST
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Validating a binary search tree verifies that every descendant respects global ordering boundaries.
The common mistake: checking only immediate children
A frequent beginner error is checking only immediate children at each node. Checking left child smaller and right child larger locally is insufficient.
// WRONG: compares each node only with its own childrenstatic boolean isValidLocal(TreeNode node) { if (node == null) return true; if (node.left != null && node.left.val >= node.val) return false; if (node.right != null && node.right.val <= node.val) return false; return isValidLocal(node.left) && isValidLocal(node.right);}// Root 10, right child 15, and 15's left child 6: this returns true, yet 6 < 10 breaks the BSTConsider root 10 with right child 15, where 15 has left child 6. Locally, 6 is less than 15, and 15 is greater than 10. However, 6 sits in the right subtree of 10, violating global ordering. A brute-force check scans every subtree for min and max, taking O(n squared) time.
A correct algorithm must enforce that every descendant respects ancestor constraints.
Example 1 · Brute force: compare every node with its whole subtrees (O(n²) time, O(h) space)
public class ValidateBruteDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
static boolean allSmaller(TreeNode node, int limit) { if (node == null) return true; return node.val < limit && allSmaller(node.left, limit) && allSmaller(node.right, limit); }
static boolean allLarger(TreeNode node, int limit) { if (node == null) return true; return node.val > limit && allLarger(node.left, limit) && allLarger(node.right, limit); }
static boolean isValidBST(TreeNode node) { if (node == null) return true; return allSmaller(node.left, node.val) && allLarger(node.right, node.val) && isValidBST(node.left) && isValidBST(node.right); }
public static void main(String[] args) { TreeNode valid = new TreeNode(2); valid.left = new TreeNode(1); valid.right = new TreeNode(3);
TreeNode invalid = new TreeNode(5); invalid.left = new TreeNode(1); invalid.right = new TreeNode(4); invalid.right.left = new TreeNode(3); invalid.right.right = new TreeNode(6);
System.out.println("Tree 1 valid: " + isValidBST(valid)); System.out.println("Tree 2 valid: " + isValidBST(invalid)); }}Tree 1 valid: true Tree 2 valid: false
What this code does
- At every node the code scans the entire left subtree for a value that is too big and the entire right subtree for one that is too small.
- It is correct, but a node near the top is scanned again for every ancestor above it. On a chain that adds up to O(n²) steps.
Find the bug
Find the validation bug
Select the line that is wrong.
A BST must reject a node equal to its limit.
Round 1 of 3Validating with recursive min and max bounds
A linear time algorithm passes allowable value bounds downward. Initialize the root with lower bound negative infinity and upper bound positive infinity.
Example 2 · Optimal: pass a lower and upper bound down (O(n) time, O(h) space)
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static boolean isValidBST(TreeNode root) { return validate(root, Long.MIN_VALUE, Long.MAX_VALUE); }
static boolean validate(TreeNode node, long min, long max) { if (node == null) return true; if (node.val <= min || node.val >= max) return false; return validate(node.left, min, node.val) && validate(node.right, node.val, max); }
public static void main(String[] args) { TreeNode valid = new TreeNode(2); valid.left = new TreeNode(1); valid.right = new TreeNode(3);
TreeNode invalid = new TreeNode(5); invalid.left = new TreeNode(1); invalid.right = new TreeNode(4); invalid.right.left = new TreeNode(3); invalid.right.right = new TreeNode(6);
System.out.println("Tree 1 valid: " + isValidBST(valid)); System.out.println("Tree 2 valid: " + isValidBST(invalid)); }}Tree 1 valid: true Tree 2 valid: false
What this code does
- Recursive helper passes allowable numerical bounds to every node.
- Long bounds prevent overflow when tree values contain Integer.MIN_VALUE.
- Both left and right child subtrees must satisfy restricted ranges.
- Why it is faster: each node is checked once against a range that already carries every ancestor's limits, so no subtree is scanned twice.
When recursing left, the current node value becomes the new upper bound. When recursing right, the current node value becomes the new lower bound. If any node value falls outside its bounds, the tree is invalid. Trace tree [10, 5, 15, null, null, 6, 20]. Node 15 receives range (10, infinity). Its left child 6 receives range (10, 15). Because 6 is not greater than 10, the validation immediately detects the violation.
The inorder traversal validation check
An alternate validation technique leverages the inorder traversal property. In a valid binary search tree, an inorder traversal visits keys in strictly increasing order.
Example 3 · Also O(n): inorder walk with the previous value (O(h) space)
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static Long prev = null;
static boolean isValidInorder(TreeNode root) { prev = null; return inorderCheck(root); }
static boolean inorderCheck(TreeNode node) { if (node == null) return true; if (!inorderCheck(node.left)) return false;
if (prev != null && node.val <= prev) { return false; } prev = (long) node.val;
return inorderCheck(node.right); }
public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(15); root.right.left = new TreeNode(12);
System.out.println("Is valid BST: " + isValidInorder(root)); }}Is valid BST: true
What this code does
- Inorder traversal visits nodes in sequential numerical order.
- The previous value variable confirms strictly increasing sequence.
- Any non-increasing step immediately returns false.
- Why it is fast: a valid BST gives a strictly increasing inorder sequence, so one comparison per node with the previous value is enough.
Example 4 · Also O(n): iterative inorder with a stack (O(h) space)
import java.util.Stack;
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static boolean isValidIterative(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); TreeNode curr = root; TreeNode prev = null;
while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); if (prev != null && curr.val <= prev.val) { return false; } prev = curr; curr = curr.right; } return true; }
public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(2); root.right = new TreeNode(5);
System.out.println("Iterative check: " + isValidIterative(root)); }}Iterative check: true
What this code does
- An explicit stack emulates depth-first inorder traversal.
- Each popped node is compared against the previously popped node.
- The loop short-circuits to false if ordering is violated.
Maintain a pointer or variable holding the previously visited node value. During inorder traversal, compare the current node value against the previous value. If current value is less than or equal to previous value, return false. This method runs in linear O(n) time and checks strict ascending order naturally.
Next step
Check your understanding
10 quick questions