AlgoMaster Logo

Binary Tree Zigzag Level Order Traversal

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. BFS using Deque

Intuition:

The 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.

Algorithm:

  1. Initialize a Deque to serve as a queue for BFS.
  2. Use a boolean leftToRight to keep track of the direction of the traversal.
  3. For each level, determine its size, and traverse the nodes. Depending on leftToRight, we either add nodes to a list normally or reverse them.
  4. Switch the direction for the next level.
  5. Add the completed levels to the results and return once all levels are processed.

Code:

2. BFS with Two Stacks

Intuition:

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.

Algorithm:

  1. Use two stacks: one for current processing (currentLevel) and another for the next level (nextLevel).
  2. Toggle the direction of node addition to the nextLevel stack with a boolean leftToRight.
  3. Pop nodes from currentLevel, and based on the direction, push their children onto nextLevel in appropriate order.
  4. When currentLevel is empty, swap stacks and repeat until all nodes are processed.

Code: