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
Example 1
Output: true
Example 2
Output: false
Explanation: at the root, the left subtree has height 3 and the right subtree has height 1.
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]null
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.
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)
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 heightheight
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 isBalancedheight
- First,
callsisBalanced on the root, and returns true unless the answer is -1.height - In
, an empty subtree (height ) returns 0.node == null - Otherwise, call
on the left child and keep the answer inheight . Ifleft is -1, return -1 without visiting the right child.left - Call
on the right child and keep the answer inheight . Ifright is -1, or the two heights differ by more than one (right ), return -1.Math.abs(left - right) > 1 - If the node passes, return its height,
.1 + Math.max(left, right)
Besides these two methods, the class has a small TreeNodebuildmain
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:
[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 truefalse
Look at the third line, [1, 2, 2, 3, null, null, 3, 4, null, null, 4] -> falsefalse
The chain [1, null, 2, null, 3]true
Complexity
Each node is visited at most once, and the only memory is the chain of height
- Time: O(n) for a tree of n nodes, because
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.height - 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