-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevelOrderReverse.java
More file actions
32 lines (28 loc) · 899 Bytes
/
LevelOrderReverse.java
File metadata and controls
32 lines (28 loc) · 899 Bytes
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
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> sol=new ArrayList<>();
BFS(root,sol);
Collections.reverse(sol);
return sol;
}
private static void BFS(TreeNode root,List<List<Integer>> sol){
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);
}
}
sol.add(subsol);
}
}
}