Binary Tree Zigzag Level Order Traversal
Read a binary tree level by level, switching between left to right and right to left on each new level.
Given the root
Example 1
Output: [[3], [20, 9], [15, 7]]
Example 2
Output: [[1]]
The Idea
Think of a tractor ploughing a field. It drives the first row from west to east, turns around, drives the second row from east to west, and keeps turning at the end of every row. A zigzag reading of a tree moves the same way, but its rows are the levels of the tree.
In Example 1, the array [3, 9, 20, null, null, 15, 7]
Read straight across, left to right every time, the levels give [3][9, 20][15, 7][[3], [20, 9], [15, 7]]
The walk itself does not have to change. Visit every level left to right, as usual, and change only where each value is written into its level's list. Look at the picture below.
In the row labelled level 1, the visit order is 9, then 20. This level goes right to left, so each value is added to the front of the list. First 9 makes [9][20, 9]
So the zigzag is only about placement. The walk underneath is the plain level-by-level walk of
Solution Approach
Turning that idea into code means deciding how to visit one level at a time, where each value goes in its level's list and when to switch direction, and seeing why reversing the visit itself goes wrong.
Visiting one level at a time
How do we visit the nodes level by level? A queue does it, because nodes leave a queue in the order they joined. The queue begins holding just the root. Take a node out, then put its left child and its right child at the back. Children always join behind every node already waiting, so all of level 1 leaves the queue before any node of level 2.
Where does one level end? At the start of each round, the queue holds exactly the nodes of one level. In Example 1, once 3 has left, the queue holds 9 and 20. Its size, 2, says how many nodes to take out before level 2 begins.
Placing each value in the level's list
Where does a value go? On a left-to-right level, at the end of the list. On a right-to-left level, at the front, which reverses that level while it is read. Java's LinkedListaddLastaddFirstArrayListadd(0, x)
As an alternative, every value can be added to the end, and every second list reversed with Collections.reverse
Switching direction
When does the direction change? Once per level, right after its last node leaves the queue. A booleanleftToRighttrue
Reversing the visiting order instead
Would it be simpler to queue the children right before left on alternate levels, so that they leave the queue already reversed? That fixes level 1 but breaks the levels below it. Take the full tree of the numbers 1 to 15: level 0 is 1, level 1 is 2 and 3, level 2 is 4 to 7, and level 3 is 8 to 15.
Level 1 then leaves the queue as 3, 2, so the children of 3 are queued ahead of the children of 2. Level 2 comes out as [6, 7, 4, 5][4, 5, 6, 7]
Java Solution
The method zigzagLevelOrder
- First, create
, the list of lists to return, andlevels , anqueue used as the queue. IfArrayDeque is notroot , add it tonull . An empty tree leavesqueue empty, and the method returns an emptyqueue .levels - Set
toleftToRight , because the root's level is read left to right.true - A
loop runs once per level, as long aswhile is not empty. It saves the number of nodes waiting inqueue and createssize , a newlevel for this level's values.LinkedList - Inside, a
loop takesfor nodes out ofsize withqueue . Each value goes to the end ofpoll withlevel whenaddLast isleftToRight , and to the front withtrue otherwise. The node's left and right children, when they exist, join the back ofaddFirst .queue - After the
loop, addfor tolevel and fliplevels . WhenleftToRight is finally empty, returnqueue .levels
The class also has a small TreeNodebuildnullmain
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class ZigzagLevelOrderTraversal {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> levels = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
queue.add(root);
}
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size(); // nodes on this level
LinkedList<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (leftToRight) {
level.addLast(node.val);
} else {
level.addFirst(node.val); // same visiting order, reversed placement
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
levels.add(level);
leftToRight = !leftToRight; // next level goes the other way
}
return levels;
}
// Builds a tree from the row-by-row form, where null marks 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;
}
public static void main(String[] args) {
System.out.println(zigzagLevelOrder(build(3, 9, 20, null, null, 15, 7)));
System.out.println(zigzagLevelOrder(build(1)));
System.out.println(zigzagLevelOrder(build()));
System.out.println(zigzagLevelOrder(
build(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)));
System.out.println(zigzagLevelOrder(build(1, 2, null, 3, null, 4)));
}
}
Running it prints:
[[3], [20, 9], [15, 7]]
[[1]]
[]
[[1], [3, 2], [4, 5, 6, 7], [15, 14, 13, 12, 11, 10, 9, 8]]
[[1], [2], [3], [4]]
Example 1 gives [[3], [20, 9], [15, 7]][]while
Look at the fourth line, the tree of 1 to 15. Level 2 reads [4, 5, 6, 7][6, 7, 4, 5][[1], [2], [3], [4]]
Complexity
The work is one pass through the tree, with a queue holding the nodes that wait for their turn.
- Time: O(n), because each of the n nodes joins the queue once, leaves it once, and goes into its level's list with an
oraddFirst that takes constant time.addLast - Space: O(w) besides the output, where w is the largest number of nodes on one level, because the queue holds the rest of one level plus the children already queued from it.