Binary Tree Zigzag Level Order Traversal Problem
Description
LeetCode Problem 103.
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
Solution
Approach: Level-by-Level BFS, Reversing Every Other Level
This is level order traversal with a twist only in how each level is written out. The traversal itself stays the same: keep the nodes of one level in a list, left to right, and build the next level from their children, left child before right child.
- Start with
current = [root](or nothing for an empty tree) andleftToRight = true. - For each level:
- collect the values of
currentfrom left to right; - build
nextLevelfrom the children, left before right; - if
leftToRightis false, reverse the collected values; - append the values to the answer, flip
leftToRight, and move on tonextLevel.
- collect the values of
The detail that matters: reverse the values, not the order in which the next level is built. If we reversed current itself and then added its children, the next level would come out in the wrong order, and the levels below it too. Keeping the nodes always left to right means each level only has to decide its own direction.
For root = [3,9,20,null,null,15,7]: level 0 is [3] (left to right), level 1 holds 9, 20 and is written as [20,9], and level 2 is [15,7].
Complexity: O(n) time, since each node is visited once and each value is reversed at most once, and O(w) extra space, where n is the number of nodes and w is the largest number of nodes on one level.
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
current = [root] if root is not None else [] # the nodes of one level, left to right
left_to_right = True
while current:
values = []
next_level = []
for node in current:
values.append(node.val)
# children in left-to-right order form the next level
if node.left is not None:
next_level.append(node.left)
if node.right is not None:
next_level.append(node.right)
if not left_to_right:
values.reverse() # only the output is reversed, never the nodes
levels.append(values)
left_to_right = not left_to_right
current = next_level
return levels
Now write it from memory
Close the write-up and solve it yourself against the tests.