MrainW's Home

All things come to those who wait!

0%

LeetCode 103. Binary Tree Zigzag Level Order Traversal

Question

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:

1
2
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]

Example 2:

1
2
Input: root = [1]
Output: [[1]]

Example 3:

1
2
Input: root = []
Output: []

Solution

  • Solution1 – BFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root != null) q.offer(root);
while(!q.isEmpty()){
int size = q.size();
List<Integer> level = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode cur = q.poll();
if (res.size() % 2 == 0) level.add(cur.val);
else level.add(0, cur.val);
if(cur.left != null) q.offer(cur.left);
if(cur.right != null) q.offer(cur.right);
}
res.add(level);
}
return res;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels