Skip to main content

Binary Tree Zigzag Level Order Traversal


Binary Tree Zigzag Level Order Traversal: 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:

image

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

Try this Problem on your own or check similar problems:

  1. Binary Tree Level Order Traversal
  2. Binary Tree Level Order Traversal II
  3. Average of Levels in Binary Tree
Solution:
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root == null) return List.of();

List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
boolean isReversed = false;

q.add(root);
while(!q.isEmpty()){
int size = q.size();
List<Integer> level = new ArrayList<>();
while(size-->0){
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
level.add(node.val);
}
if(isReversed) Collections.reverse(level);
isReversed = !isReversed;
result.add(level);
}

return result;
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

We use the implementation from Binary Tree Level Order Traversal only this time with a flag isReversed which if set would reverse the current level. Since isReversed will be true (since it's alternating between true and false for every level change) only for even levels (2nd, 4th... ) we will only reverse those levels. We return the list of levels as our result. Space and time complexity remain unchanged.