-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJuly22_2020.java
46 lines (34 loc) · 1.15 KB
/
July22_2020.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// zigzag level order traversal - Binary Tree
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int level = 0;
while(!q.isEmpty()) {
int len = q.size();
List<Integer> levelSet = new ArrayList<>();
for(int i=0; i < len; i++){
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
if(level % 2 == 0){
levelSet.add(node.val);
}
else {
levelSet.add(0, node.val);
}
}
result.add(levelSet);
level++;
}
return result;
}
}