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).
Output: [[3],[20,9],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
[0, 2000].-100 <= Node.val <= 100The zigzag level order traversal requires alternating the direction of each level while we traverse the binary tree. By utilizing a Deque, we can alternate between adding levels to the front or the back, effectively reversing the order of nodes as needed.
Deque to serve as a queue for BFS.leftToRight to keep track of the direction of the traversal.leftToRight, we either add nodes to a list normally or reverse them.queue which stores nodes at the current level. The largest number of nodes at any level is O(N/2) in a balanced tree.Using two stacks allows us to manage two levels of processing: one for the current level and another for the next, enabling us to control the processing order explicitly.
currentLevel) and another for the next level (nextLevel).nextLevel stack with a boolean leftToRight.currentLevel, and based on the direction, push their children onto nextLevel in appropriate order.currentLevel is empty, swap stacks and repeat until all nodes are processed.