-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZagTraversal.java
More file actions
37 lines (34 loc) · 1.02 KB
/
ZigZagTraversal.java
File metadata and controls
37 lines (34 loc) · 1.02 KB
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
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> sol=new ArrayList<>();
BFS(root,sol,0);
return sol;
}
private static void BFS(TreeNode root,List<List<Integer>> sol,int level){
if(root==null)return;
Deque<TreeNode> q=new ArrayDeque<>();
q.add(root);
while(!q.isEmpty()){
List<Integer> subsol=new ArrayList<>();
int qlen=q.size();
for(int i=0;i<qlen;i++){
TreeNode curr=q.poll();
subsol.add(curr.val);
if(curr.left!=null){
q.add(curr.left);
}
if(curr.right!=null){
q.add(curr.right);
}
}
if(level%2==0){
sol.add(subsol);
}
else{
Collections.reverse(subsol);
sol.add(subsol);
}
level++;
}
}
}