Binary Tree Zigzag Level Order Traversal
LeetCode 103 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range `[0, 2000]`.
- `-100 <= Node.val <= 100`
Topics: Tree, Breadth-First Search, Binary Tree
Approachβ
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
When to use
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 475 ms)β
| Metric | Value |
|---|---|
| Runtime | 475 ms |
| Memory | N/A |
| Date | 2017-12-05 |
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
IList<IList<int>> levelOrder = new List<IList<int>>();
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
if (root != null) stack1.Push(root);
bool isOddRow = true;
while (stack1.Count != 0 || stack2.Count != 0)
{
List<int> levelNums = new List<int>();
if (isOddRow)
{
var levelSize = stack1.Count;
while(stack1.Count !=0)
{
var dequeued = stack1.Pop();
levelNums.Add(dequeued.val);
if (dequeued.left != null) stack2.Push(dequeued.left);
if (dequeued.right != null) stack2.Push(dequeued.right);
}
}
else
{
while(stack2.Count != 0)
{
var poppedElement = stack2.Pop();
levelNums.Add(poppedElement.val);
if (poppedElement.right != null) stack1.Push(poppedElement.right);
if (poppedElement.left != null) stack1.Push(poppedElement.left);
}
}
isOddRow = !isOddRow;
levelOrder.Add(levelNums);
}
return levelOrder;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.