Maximum Width of Binary Tree
Find the widest level of a binary tree, counting the empty spots between its outermost nodes.
Given the root of a binary tree, return the width of its widest level. A level's width counts every position from its leftmost node to its rightmost node, including the empty spots in between, as if that stretch were full of nodes. The tree is written row by row, top to bottom and left to right, with null
Example 1
Output: 4
Explanation: the last level runs from 5 to 9 and covers four positions, one of them empty.
Example 2
Output: 7
Explanation: the last level runs from 6 to 7, with five empty positions between them.
The Idea
Picture the tree of Example 1 drawn on paper. At the top sits the root, 1. Below it are its two children, 3 and 2. One row further down, 3 has two children, 5 and 3, but 2 has only a right child, 9. Each row of the drawing, made of the nodes at the same distance from the root, is called a level.
How wide is the last level? It holds three nodes, yet the answer is 4. The spot where the left child of 2 would go is empty, and it still counts, because it lies between 5 and 9. So a level's width depends on where its outermost nodes sit, not on how many nodes it has. That raises a question: how can we tell where a node sits, when the spots around it may be empty?
We can give every spot on a level a number, its position, counting from 0 on the left as if every node above had both children. Every node has room for two children right below it. So a node at position p has its left child at position 2p and its right child at position 2p + 1. Look at the picture below.
On the middle level, 3 is at position 0 and 2 at position 1. The children of 3 land at positions 0 and 1. The children of 2 would land at positions 2 and 3. Its left child is missing, so position 2 is marked empty, and 9 takes position 3.
The bracket under the last level spans positions 0 to 3, and 3 - 0 + 1 gives 4. So the width of a level is the position of its last node, minus the position of its first node, plus one. The empty spot never has to be stored: 9 gets position 3 straight from its parent. The column headed "width of level" lists 1, 2 and 4, and the largest of them, 4, is the answer.
Solution Approach
Turning that idea into code means settling three things: how to visit the tree one level at a time, how to carry each node's position along, and how to keep the positions from growing too large. Along the way, a simpler way of counting empty spots shows why positions are worth the trouble.
Visiting one level at a time
How do we get the nodes of one level together, left to right? A queue does it: a list where items join at the back and leave from the front, in the order they came. Start with the root in it. Take a node from the front, and put its children, left first, at the back.
When a level begins, the queue holds exactly the nodes of that level, in order. Note how many there are, take that many from the front, and the children they add make up the next level. Walking a tree this way, level by level, is called level-order traversal, or breadth-first search.
Carrying each node's position
Where does a node's position come from? From its parent, so each queue entry holds a node together with its position. The root goes in at position 0, and a node at position p puts its children in at 2p and 2p + 1. For each level, the first entry taken off the queue has the first position, and the last entry has the last one.
A simpler idea is to put a placeholder in the queue for every missing child and count the placeholders too. It works for small trees, but empty spots multiply. Take a root with a chain of 30 left children down the left side and a chain of 30 right children down the right side. That is only 61 nodes, yet the last level spans 230 positions, over a billion, almost all of them placeholders. Positions skip all of that: the two real nodes simply carry the numbers 0 and 230 - 1.
Keeping the positions small
Why would positions grow too large? They double on every level. Take a chain of 100 levels, each node the right child of the one above. The node on level 100 would have a position close to 299, while a Java long
Only the distance between positions on the same level matters, so each level can start counting again from 0. Before using a node's position, subtract the position of the level's first node. The leftmost node then has position 0, and every other position on the level stays below the level's width. Shifting the numbers like this is called re-basing.
Java Solution
The method widthOfBinaryTree
- First, if
isroot , the tree has no levels, so return 0.null - Create
, anqueue (Java's queue backed by an array) ofArrayDeque values.Entry is a record, a short way to write a class that only holds data, and it holds a node and its position. Add the root at position 0. A variableEntry , starting at 0, keeps the widest level found so far.best - An outer
loop handles one level per round, until the queue is empty. It saves the number of entries inwhile , and the position of the front entry, the level's first node, insize .first - Inside, a
loop takesfor entries off the queue. For each one it re-bases the position intosize by subtractingpos , stores it infirst , and adds the node's children atlast and2 * pos .2 * pos + 1 - After the
loop, the level runs from position 0 tofor , so its width islast . Keep it inlast + 1 if it is larger than the width already there.best - When the queue is empty, every level has been measured, and the method returns
as anbest .int
The class also has a small TreeNodebuildrunmain
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
public class MaximumWidthOfBinaryTree {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
record Entry(TreeNode node, long pos) {} // a node and its position on its level
public static int widthOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
Queue<Entry> queue = new ArrayDeque<>();
queue.add(new Entry(root, 0));
long best = 0;
while (!queue.isEmpty()) {
int size = queue.size(); // number of nodes on this level
long first = queue.peek().pos();
long last = 0;
for (int i = 0; i < size; i++) {
Entry e = queue.poll();
long pos = e.pos() - first; // re-base: leftmost node becomes 0
last = pos;
if (e.node().left != null) {
queue.add(new Entry(e.node().left, 2 * pos));
}
if (e.node().right != null) {
queue.add(new Entry(e.node().right, 2 * pos + 1));
}
}
best = Math.max(best, last + 1); // positions 0 to last on this level
}
return (int) best;
}
// builds a tree from the 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> parents = new ArrayDeque<>();
parents.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = parents.poll();
if (values[i] != null) {
parent.left = new TreeNode(values[i]);
parents.add(parent.left);
}
i++;
if (i < values.length && values[i] != null) {
parent.right = new TreeNode(values[i]);
parents.add(parent.right);
}
i++;
}
return root;
}
static void run(Integer[] values) {
System.out.println(Arrays.toString(values) + " -> " + widthOfBinaryTree(build(values)));
}
public static void main(String[] args) {
run(new Integer[] {1, 3, 2, 5, 3, null, 9});
run(new Integer[] {1, 3, 2, 5, null, null, 9, 6, null, 7});
run(new Integer[] {1});
run(new Integer[] {1, 2, null, 3});
run(new Integer[] {});
// 100 levels of right children only, then two children under the last one
List<Integer> deep = new ArrayList<>(List.of(1));
for (int level = 2; level <= 100; level++) {
deep.add(null);
deep.add(level);
}
deep.add(101);
deep.add(102);
int width = widthOfBinaryTree(build(deep.toArray(new Integer[0])));
System.out.println("right-only chain of 100 levels, then two children -> " + width);
}
}
Running it prints:
[1, 3, 2, 5, 3, null, 9] -> 4
[1, 3, 2, 5, null, null, 9, 6, null, 7] -> 7
[1] -> 1
[1, 2, null, 3] -> 1
[] -> 0
right-only chain of 100 levels, then two children -> 2
Example 1 prints 4, the bracket in the picture, and Example 2 prints 7: on its last level, 6 sits at position 0 and 7 at position 6. The line for [1, 2, null, 3][]
The last line prints 2 for the two children at the bottom of the chain. Without re-basing, they would have positions 2100 - 2 and 2100 - 1. A copy of the method without re-basing, run on the same tree, saw them as -2 and -1: the numbers had run past the largest long
Complexity
The method takes every node off the queue once, and the queue never holds more than one level plus part of the next.
- Time: O(n), because each of the n nodes enters and leaves the queue once, and handling it costs one subtraction and at most two new entries.
- Space: O(w), because the queue holds at most the real nodes of one level and the children already added from it, where w is the largest number of real nodes on one level, not counting empty spots.