103 Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal

1. Question

Given a binary tree, return thezigzag level ordertraversal 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],
1
3
2
/ \
3
9 20
4
/ \
5
15 7
Copied!
return its zigzag level order traversal as:
1
[
2
[3],
3
[20,9],
4
[15,7]
5
]
Copied!

2. Implementation

(1) BFS
1
class Solution {
2
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
3
List<List<Integer>> res = new ArrayList<>();
4
if (root == null) {
5
return res;
6
}
7
8
Queue<TreeNode> queue = new LinkedList<>();
9
queue.add(root);
10
boolean reversed = false;
11
List<Integer> level = null;
12
int depth = 0;
13
14
while (!queue.isEmpty()) {
15
int size = queue.size();
16
level = new ArrayList<>();
17
18
for (int i = 0; i < size; i++) {
19
TreeNode curNode = queue.remove();
20
21
if (depth % 2 == 0) {
22
level.add(curNode.val);
23
}
24
else {
25
level.add(0, curNode.val);
26
}
27
28
if (curNode.left != null) {
29
queue.add(curNode.left);
30
}
31
32
if (curNode.right != null) {
33
queue.add(curNode.right);
34
}
35
}
36
res.add(level);
37
++depth;
38
}
39
return res;
40
}
41
}
Copied!
(2) DFS
1
class Solution {
2
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
3
List<List<Integer>> res = new ArrayList<>();
4
getZigzagLevelOrderByDFS(root, 0, res);
5
return res;
6
}
7
8
public void getZigzagLevelOrderByDFS(TreeNode node, int depth, List<List<Integer>> res) {
9
if (node == null) {
10
return;
11
}
12
13
if (res.size() == depth) {
14
res.add(new ArrayList<>());
15
}
16
17
if (depth % 2 == 0) {
18
res.get(depth).add(node.val);
19
}
20
else {
21
res.get(depth).add(0, node.val);
22
}
23
24
getZigzagLevelOrderByDFS(node.left, depth + 1, res);
25
getZigzagLevelOrderByDFS(node.right, depth + 1, res);
26
}
27
}
Copied!

3. Time & Space Complexity

BFS: 时间复杂度:O(n) , 空间复杂度:O(n)
DFS: 时间复杂度:O(n), 空间复杂度: O(n)