Leetcode 103. Binary Tree Zigzag Level Order Traversal
The problem is defined as follows:
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).
Answer: Yes, the problem guarantees a non-empty tree, and if the tree is empty, we will return an empty list.
Answer: No specific constraints are mentioned, so we assume the tree can have any number of nodes.
Queue
to facilitate BFS traversal.List<List<Integer>>
to store the final zigzag level order traversal.import java.util.*;
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> levelList = new ArrayList<>(levelSize);
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
if (leftToRight) {
levelList.add(currentNode.val);
} else {
levelList.add(0, currentNode.val); // Add to the front if it's right-to-left
}
if (currentNode.left != null) {
queue.add(currentNode.left);
}
if (currentNode.right != null) {
queue.add(currentNode.right);
}
}
result.add(levelList);
leftToRight = !leftToRight; // Toggle the direction
}
return result;
}
// TreeNode definition
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
O(N)
where N
is the number of nodes in the binary tree.
O(N)
in the worst case for the queue, where the largest possible queue size could be the entire level (in the case of a full binary tree).This concludes our solution to the zigzag level order traversal of a binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?