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 true if it is a valid binary search tree and false if it is not. In a valid binary search tree, every value below a node on its left side is strictly smaller than the node's value, and every value below it on its right side is strictly larger. This must hold at every node. Trees are written row by row, from the top, with null for a missing child.

Example 1
Input: root = [2, 1, 3]
Output: true
Example 2
Input: root = [5, 1, 4, null, null, 3, 6]
Output: false
Explanation: 4 is on the right side of 5 but is smaller than 5.
Example 3
Input: root = [5, 4, 6, null, null, 3, 7]
Output: false
Explanation: every parent is in order with its own children, but 3 is on the right side of 5.
Solution

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 tree of Example 3 with the range each node must fall in: 5 any value, 4 below 5, 6 above 5, 7 above 6, and 3 between 5 and 6. 3 is not above 5, so the tree is invalid.

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. It never compares 3 with 5, because 5 is not 3's parent.

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, low and high. If the node's value is not strictly between them, the answer is false. Otherwise the method calls itself on the left child with high replaced by the node's value, and on the right child with low replaced by it.

The comparisons are strict, so a value equal to a limit fails. In the tree [2, 2, 2], the left child 2 is not smaller than its parent 2, and the tree is not a BST. A missing child is an empty subtree, which breaks no rule, so the method returns true for it.

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_VALUE or as large as Integer.MAX_VALUE. If those two were the starting limits, a root holding 2147483647 would equal the upper limit and fail the strict check. So the limits are long values, starting at Long.MIN_VALUE and Long.MAX_VALUE, which lie beyond any value a node can hold.

Java Solution

The class has a small TreeNode class, with a value and links to a left and a right child, and a helper build that makes a tree from its row-by-row form. The check itself works in these steps:

  1. First, isValidBST(root) calls a helper method, valid, with the root and the widest range: Long.MIN_VALUE as low and Long.MAX_VALUE as high.
  2. In valid, a null node is an empty subtree, so it returns true.
  3. Otherwise it compares node.val with both limits. If the value is less than or equal to low, or greater than or equal to high, it returns false.
  4. If the value is in range, valid checks the left subtree with the range low to node.val, then the right subtree with node.val to high. It returns true only when both checks pass, and because the two checks are joined with &&, Java skips the right subtree once the left one has failed.

The main method checks the three examples, a tree of three equal values, a single node holding 2147483647 and an empty tree, then runs the parent-and-child check, childrenOnly, on Example 3.

Java
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:

Output
[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. valid reaches 3 with the range 5 to 6 and returns false, while childrenOnly finds every parent in order with its children and prints true, the wrong answer.

The line [2, 2, 2] -> false comes from the strict check: the left child gets the range up to 2, and 2 is not below 2. The line [2147483647] -> true shows why the limits are long. With Integer.MIN_VALUE and Integer.MAX_VALUE as the starting limits, the same one-node tree gives false. The empty tree, [], has nothing out of place, so it is valid.

Complexity

The work is one call of valid for each node and for each missing child.

  • 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. Kth Smallest Element in a BST uses that order.