題目:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
題解:
這道題跟前面一道是一樣的。。
只是存到res的結果順序不一樣罷了。
之前那個就是循序的存
這道題就是每得到一個行結果就存在res的0位置,這樣自然就倒序了。
程式碼如下:
1 public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(root == null)
4 return res;
5
6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
7 queue.add(root);
8
9 int curLevCnt = 1;
10 int nextLevCnt = 0;
11
12 ArrayList<Integer> levelres = new ArrayList<Integer>();
13
14 while(!queue.isEmpty()){
15 TreeNode cur = queue.poll();
16 curLevCnt--;
17 levelres.add(cur.val);
18
19 if(cur.left != null){
20 queue.add(cur.left);
21 nextLevCnt++;
22 }
23 if(cur.right != null){
24 queue.add(cur.right);
25 nextLevCnt++;
26 }
27
28 if(curLevCnt == 0){
29 curLevCnt = nextLevCnt;
30 nextLevCnt = 0;
31 res.add(0,levelres); //insert one by one from the beginning
32 levelres = new ArrayList<Integer>();
33 }
34 }
35 return res;
36 }
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 if(root == null)
4 return res;
5
6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
7 queue.add(root);
8
9 int curLevCnt = 1;
10 int nextLevCnt = 0;
11
12 ArrayList<Integer> levelres = new ArrayList<Integer>();
13
14 while(!queue.isEmpty()){
15 TreeNode cur = queue.poll();
16 curLevCnt--;
17 levelres.add(cur.val);
18
19 if(cur.left != null){
20 queue.add(cur.left);
21 nextLevCnt++;
22 }
23 if(cur.right != null){
24 queue.add(cur.right);
25 nextLevCnt++;
26 }
27
28 if(curLevCnt == 0){
29 curLevCnt = nextLevCnt;
30 nextLevCnt = 0;
31 res.add(0,levelres); //insert one by one from the beginning
32 levelres = new ArrayList<Integer>();
33 }
34 }
35 return res;
36 }