题目
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], ]
和之前的广度遍历一样,只不过,考察arraylist的反转会不会
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
if(root==null){
return ans;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int num =0;
int count =1;
while(!queue.isEmpty()){
TreeNode cur = queue.remove();
temp.add(cur.val);
count--;
if(cur.left!=null){
queue.add(cur.left);
num++;
}
if(cur.right!=null){
queue.add(cur.right);
num++;
}
if(count==0){
ans.add(new ArrayList<Integer>(temp));
temp.clear();
count = num;
num =0;
}
}
ArrayList<ArrayList<Integer>> ans2 = new ArrayList<ArrayList<Integer>>();
for(int i =ans.size()-1;i>=0;i--){
ans2.add(ans.get(i));
}
return ans2;
}
}