Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Approach
Use a deque to allow insertion at both ends. For odd-nmubered levels (1-indexed), add nodes to the tail; for even-numbered levels, add nodes to the head.
Solution
- Handle edge case: if root is null, return empty list.
- Initialize result list
resand a queuedequecontaining root. - While deque is not empty:
- Create a new linked list
tmpfor current level. - Iterate over current level nodes (size of deque):
- Poll node from front of deque.
- If
res.size() % 2 == 0(odd level), add node.val totmp's tail; else add to head. - Add left and right children to deque if not null.
- Add
tmptores.
- Create a new linked list
- Return
res.
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if (root != null) queue.add(root);
while (!queue.isEmpty()) {
LinkedList<Integer> tmp = new LinkedList<>();
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
if (res.size() % 2 == 0) tmp.addLast(node.val);
else tmp.addFirst(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(tmp);
}
return res;
}
}
Complexity Analysis:
- Time complxeity: O(n), where n is the number of nodes.
- Space complexity: O(n) for the queue and result.