Balanced Binary Tree

Check whether every node of a binary tree has left and right subtrees of nearly equal height.

Given the root of a binary tree, return true if the tree is height-balanced: at every node, the heights of the left and right subtrees differ by at most one. The tree is written row by row, from left to right, with null for a missing child.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: true
Example 2
Input: root = [1, 2, 2, 3, 3, null, null, 4, 4]
Output: false
Explanation: at the root, the left subtree has height 3 and the right subtree has height 1.
Solution

The Idea

A binary tree is a set of nodes in which each node holds a value and has at most two children, a left one and a right one. It is drawn like a family tree: one node, the root, at the top, and each node's children one row below it. A node together with everything below it is called a subtree.

In Example 1, [3, 9, 20, null, null, 15, 7] puts 3 at the root and 9 and 20 in the row below. The two null values say that 9 has no children, and 15 and 7 are the children of 20.

The height of a subtree is the number of nodes on its longest path downward. A node with no children, called a leaf, has height 1, and an empty subtree has height 0. So in Example 1, the root's left subtree, just 9, has height 1, and its right subtree, 20 with 15 and 7, has height 2. They differ by one, which is allowed. Every node below passes too, so the answer is true.

Example 2 is deeper. Look at the picture below: it shows the tree of Example 2, with the height of each node's subtree written next to the node.

The tree of Example 2 with the height of each subtree. The two 4s have height 1, the 3 above them height 2, the other 3 height 1, the left 2 height 3 and the right 2 height 1. At the root 1, left height 3 and right height 1 differ by 2, so the tree is not balanced.

Start at the bottom. The two 4s are leaves, so each has height 1. The 3 above them has height 2, one more than its taller child. The other 3 is a leaf, with height 1. The left 2 sits above subtrees of heights 2 and 1, so it gets height 3, and the right 2 is a leaf. At the root, as the orange note says, left height 3 and right height 1 differ by 2, so the tree is not balanced.

Notice how each height in the picture came about. It was worked out from the two heights just below it, never by walking down the tree again. Can the balance check come along for free? It can, because the two heights a node needs for its own height are exactly the two heights it must compare. One walk from the leaves up gives every height and checks every node on the way.

Solution Approach

Turning that idea into code starts with the most direct check, and why it repeats work. Then two things need settling: how each node gets its height from its children, and how a node reports trouble below it.

Checking each node separately

What is the most direct way? At each node, measure the height of the left subtree and of the right one, compare them, and then do the same for both children. But measuring a height walks the whole subtree. The root's check walks the whole tree, each child's check walks its half again, and so on down.

In a tree that is balanced all the way down, a node ten rows below the root has its height measured ten times, once for every node above it. For n nodes that adds up to about n log n steps, where one walk would do.

Heights from the bottom up

How does a node get its height without walking down again? It asks its children. A method height(node) returns 0 for an empty subtree. Otherwise it calls itself on the left child and on the right child, and returns one more than the larger answer. A method that calls itself on smaller parts like this is called recursive.

A node finishes only after both of its children have answered, so the heights come back from the leaves up, in the same order as in the picture. Before returning, the node compares the two answers it already holds, and that is the balance check.

Reporting an unbalanced subtree

What should height return when a node fails the check? Then the whole tree is not balanced, whatever happens above, and that is all the callers need to know. A real height is never negative, so height returns -1 to mean "not balanced". Any node that gets -1 from a child returns -1 at once, so the -1 travels up to the root.

The order of the two calls saves some work too. The left child is asked first, and if it answers -1, the right child is never visited.

Java Solution

The methods isBalanced and height work in these steps:

  1. First, isBalanced calls height on the root, and returns true unless the answer is -1.
  2. In height, an empty subtree (node == null) returns 0.
  3. Otherwise, call height on the left child and keep the answer in left. If left is -1, return -1 without visiting the right child.
  4. Call height on the right child and keep the answer in right. If right is -1, or the two heights differ by more than one (Math.abs(left - right) > 1), return -1.
  5. If the node passes, return its height, 1 + Math.max(left, right).

Besides these two methods, the class has a small TreeNode class and a build helper that turns the row-by-row list into a tree, so each test reads like the examples. The main method runs both examples, a tree whose root passes but a lower node fails, a chain of three nodes, a single node and an empty tree.

Java
import java.util.Arrays;

public class BalancedBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }

    // Height of the subtree in nodes, or -1 if some node in it is not balanced.
    private static int height(TreeNode node) {
        if (node == null) {
            return 0;                          // an empty subtree has height 0
        }
        int left = height(node.left);
        if (left == -1) {
            return -1;                         // unbalanced below: skip the right side
        }
        int right = height(node.right);
        if (right == -1 || Math.abs(left - right) > 1) {
            return -1;                         // unbalanced below, or right here
        }
        return 1 + Math.max(left, right);
    }

    // Builds a tree from level order, row by row; null marks a missing child.
    static TreeNode build(Integer[] values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode[] nodes = new TreeNode[values.length];
        nodes[0] = new TreeNode(values[0]);
        int parent = 0;
        for (int i = 1; i < values.length; i++) {
            while (nodes[parent] == null) {
                parent++;
            }
            if (values[i] != null) {
                nodes[i] = new TreeNode(values[i]);
                if (i % 2 == 1) {
                    nodes[parent].left = nodes[i];
                } else {
                    nodes[parent].right = nodes[i];
                }
            }
            if (i % 2 == 0) {
                parent++;
            }
        }
        return nodes[0];
    }

    static void check(Integer... values) {
        System.out.println(Arrays.toString(values) + " -> " + isBalanced(build(values)));
    }

    public static void main(String[] args) {
        check(3, 9, 20, null, null, 15, 7);
        check(1, 2, 2, 3, 3, null, null, 4, 4);
        check(1, 2, 2, 3, null, null, 3, 4, null, null, 4);
        check(1, null, 2, null, 3);
        check(1);
        check();
    }
}

Running it prints:

Output
[3, 9, 20, null, null, 15, 7] -> true
[1, 2, 2, 3, 3, null, null, 4, 4] -> false
[1, 2, 2, 3, null, null, 3, 4, null, null, 4] -> false
[1, null, 2, null, 3] -> false
[1] -> true
[] -> true

Example 1 gives true and Example 2 gives false, with the root's subtrees at heights 3 and 1 as in the picture.

Look at the third line, [1, 2, 2, 3, null, null, 3, 4, null, null, 4] -> false. Both of the root's subtrees have height 3 here, so comparing heights only at the root would answer true. But the left 2 has a 3 and a 4 below it on the left, height 2, and nothing on the right, height 0. That node returns -1, the -1 travels up, and the answer is false. This is why every node is checked, not only the root.

The chain [1, null, 2, null, 3] fails at the root itself: nothing on the left, height 0, against two nodes on the right, height 2. The last two lines are the smallest trees. A single node has two empty subtrees of height 0, and an empty tree has no node that could fail, so both print true.

Complexity

Each node is visited at most once, and the only memory is the chain of height calls that have not finished yet.

  • Time: O(n) for a tree of n nodes, because height runs once on each node and once on each missing child, and does a fixed amount of work besides its two calls. No height is measured twice, unlike in the direct check of each node separately.
  • Space: O(h), where h is the height of the whole tree, because the unfinished calls form one path from the root down to the current node. That is about log n calls for a balanced tree and n for a chain.

Returning a height up the tree while keeping track of another answer on the way is also how Diameter of Binary Tree works.