Validate Binary Search Tree
Check that every value in a binary tree sits in the range its ancestors allow.
Given the root of a binary tree, return truefalsenull
Example 1
Output: true
Example 2
Output: false
Explanation: 4 is on the right side of 5 but is smaller than 5.
Example 3
Output: false
Explanation: every parent is in order with its own children, but 3 is on the right side of 5.
The Idea
In Example 1, the top node, called the root, holds 2. It has two children: 1 on its left and 3 on its right. 1 is smaller than 2 and 3 is larger, so the values are in order. A tree that keeps this order everywhere is a binary search tree, or BST.
Why does the order matter? To find a value in a BST, you compare it with the root and go left if it is smaller, right if it is larger, and repeat. Each step skips one whole side of the tree. If one value is out of place, such a search goes the wrong way and misses it.
Example 2 breaks the order right at the root: 5 has 4 as its right child, and 4 is smaller than 5. A check of each node against its two children catches that. Example 3 is harder. Its root 5 has 4 on the left and 6 on the right, and 6 has 3 on the left and 7 on the right. Every parent is in order with its own children: 4 is below 5, 6 is above 5, 3 is below 6, and 7 is above 6.
Yet 3 hangs below 6, which is on the right of 5, so 3 is on the right side of 5 and should be larger than 5. Everything below a node on one side, all the way down, is called that node's subtree: 6, 3 and 7 form the right subtree of 5. So how can 3, two levels down, know about a limit that 5 set?
The answer is to hand each node the range that the nodes above it, its ancestors, allow. For 3, the ancestors are 6 and 5. Look at the picture below.
The root 5 is labelled "any value", because nothing is above it. Going left to 4 adds the limit "below 5", and going right to 6 adds "above 5". From 6, going right to 7 gives "above 6", since above 6 already means above 5.
Now look at 3, labelled "between 5 and 6". Going left from 6 adds "below 6", but the limit "above 5" from the root still holds, so both apply. 3 is below 6 but not above 5, and the tree is invalid.
So each step down keeps one limit and replaces the other. Going left, the node's value becomes the new upper limit. Going right, it becomes the new lower limit. A node is in place when its value is inside its range.
Solution Approach
Turning the range into code means settling three things: why a check of each parent against its children is not enough, how the range travels down the tree, and what range the root starts with.
Checking each parent with its children
Is it enough to compare each node with its own left and right child? It is simple and visits each node once, but Example 3 shows it answers wrong. All four parent and child pairs in that tree are in order, so the check says true
Passing the range down
How does each node get its range? A method that checks one subtree takes the subtree's top node and two limits, lowhighfalsehighlow
The comparisons are strict, so a value equal to a limit fails. In the tree [2, 2, 2]true
The root's starting range
What range does the root get? It should allow any value, but node values can be as small as Integer.MIN_VALUEInteger.MAX_VALUElongLong.MIN_VALUELong.MAX_VALUE
Java Solution
The class has a small TreeNodebuild
- First,
calls a helper method,isValidBST(root) , with the root and the widest range:valid asLong.MIN_VALUE andlow asLong.MAX_VALUE .high - In
, avalid node is an empty subtree, so it returnsnull .true - Otherwise it compares
with both limits. If the value is less than or equal tonode.val , or greater than or equal tolow , it returnshigh .false - If the value is in range,
checks the left subtree with the rangevalid tolow , then the right subtree withnode.val tonode.val . It returnshigh only when both checks pass, and because the two checks are joined withtrue , Java skips the right subtree once the left one has failed.&&
The mainchildrenOnly
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
public class ValidateBST {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static boolean isValidBST(TreeNode root) {
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
// Every value in this subtree must be strictly between low and high.
private static boolean valid(TreeNode node, long low, long high) {
if (node == null) {
return true; // an empty subtree breaks no rule
}
if (node.val <= low || node.val >= high) {
return false; // outside the allowed range
}
return valid(node.left, low, node.val) // left: node.val is the new upper limit
&& valid(node.right, node.val, high); // right: node.val is the new lower limit
}
// The tempting check: each node against its own two children only.
static boolean childrenOnly(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 childrenOnly(node.left) && childrenOnly(node.right);
}
// Builds a tree from its row-by-row form, with null for a missing child.
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = queue.poll();
if (values[i] != null) {
parent.left = new TreeNode(values[i]);
queue.add(parent.left);
}
i++;
if (i < values.length && values[i] != null) {
parent.right = new TreeNode(values[i]);
queue.add(parent.right);
}
i++;
}
return root;
}
static void check(Integer... values) {
System.out.println(Arrays.toString(values) + " -> " + isValidBST(build(values)));
}
public static void main(String[] args) {
check(2, 1, 3);
check(5, 1, 4, null, null, 3, 6);
check(5, 4, 6, null, null, 3, 7);
check(2, 2, 2);
check(2147483647);
check();
System.out.println("children-only check on [5, 4, 6, null, null, 3, 7] -> "
+ childrenOnly(build(5, 4, 6, null, null, 3, 7)));
}
}
Running it prints:
[2, 1, 3] -> true
[5, 1, 4, null, null, 3, 6] -> false
[5, 4, 6, null, null, 3, 7] -> false
[2, 2, 2] -> false
[2147483647] -> true
[] -> true
children-only check on [5, 4, 6, null, null, 3, 7] -> true
Compare the third line with the last one. Both look at Example 3. validfalsechildrenOnlytrue
The line [2, 2, 2] -> false[2147483647] -> truelongInteger.MIN_VALUEInteger.MAX_VALUEfalse[]
Complexity
The work is one call of valid
- Time: O(n), because each of the n nodes is checked against its two limits once, and an invalid tree can stop sooner.
- Space: O(h), because the recursion keeps one open call per node on the current path from the root, and h, the number of nodes on the longest such path, reaches n when every node has only one child.
A valid BST also gives its values in strictly increasing order when you read the left subtree, then the node, then the right subtree.