Search⌘ K
AI Features

Binary Tree Zigzag Level Order Traversal

Explore how to traverse a binary tree in zigzag level order using breadth-first search. This lesson helps you implement traversal that alternates direction on each tree level, enhancing your understanding of BFS applications in tree problems.

Statement

Given a binary tree, return its zigzag level order traversal. The zigzag level order traversal corresponds to traversing nodes from left to right for one level, and then right to left for the next level, and so on, reversing direction after every level.

Constraints:

  • The number of nodes in the tree is in the range 00 to 500500.

  • 100-100 \leq node.data 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Binary Tree Zigzag Level Order Traversal

1.

What will be the zigzag level order traversal of the following tree?

[0, 2, 4, 1, NULL, 3, -1, 5, 1, NULL, 6, NULL, 8]

A.

[[0], [2, 4] , [1, NULL, 3, -1], [5, 1, NULL, 6, NULL, 8]]

B.

[[0], [4, 2], [1, 3, -1], [8, 6, 1, 5]]

C.

[0, 4, 2, 1, 3, -1, 8, 6, 1, 5]

D.

[NULL]


1 / 2

Figure it out!

Here’s a game for you to play! Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in main.java in the following coding playground. You will need the provided supporting code to implement your solution.

Java
usercode > Solution.java
import java.util.*;
import ds_v1.BinaryTree.TreeNode;
// Definiton of a binary tree node class
// class TreeNode<T> {
// T data;
// TreeNode<T> left;
// TreeNode<T> right;
// TreeNode(T data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
public class Solution{
public static List<List<Integer>> zigzagLevelOrder(TreeNode<Integer> root) {
// Replace this placeholder return statement with your code
return new ArrayList<List<Integer>>();
}
}
Binary Tree Zigzag Level Order Traversal