Binary Tree Zigzag Level Order Traversal
TreesBFS
Problem Statement
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
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Solution: Breadth-First Search (BFS)
The problem can be solved efficiently using a Breadth-First Search. We traverse the tree level by level, and for each level, we decide whether to add the nodes from left to right or right to left.
Algorithm Steps
- Create a queue and add the root node.
- Keep track of the current level number.
- While the queue is not empty, get the number of nodes at the current level.
- If the level is even, add the nodes to the level list from left to right.
- If the level is odd, add the nodes to the level list from right to left.
- Enqueue the children of the nodes at the current level.
Final Result:
[ ]
Start of level. Level size: 1. Direction: left to right.
Binary Tree Zigzag Level Order Traversal Solution