-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomUpOrder.java
More file actions
39 lines (39 loc) · 1.16 KB
/
BottomUpOrder.java
File metadata and controls
39 lines (39 loc) · 1.16 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
38
39
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BottomUpOrder {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
if(root == null) return ans;
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
LinkedList<Integer> qidx = new LinkedList<Integer>();
q.offer(root);
qidx.offer(0);
while(!q.isEmpty()){
TreeNode now = q.poll();
int nowIdx = qidx.poll();
if(ans.size() ==nowIdx){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(now.val);
ans.add(0,tmp);
}else{
ans.get(0).add(now.val);
}
if(now.left != null){
q.offer(now.left);
qidx.offer(nowIdx +1);
}
if(now.right != null){
q.offer(now.right);
qidx.offer(nowIdx +1);
}
}
return ans;
}
}