在层次遍历的基础上,反转ArrayList<ArrayList<Integer>>就可以了
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
if(root == null)return lists;
Queue<TreeNode> Q = new ArrayDeque<TreeNode>();
TreeNode p = root;
Q.offer(p);
int count = 1;
while(!Q.isEmpty()){
ArrayList<Integer> list = new ArrayList<Integer>();
int nextCount = 0;
for(int i = 0;i<count;i++){
p = Q.poll();
list.add(p.val);
if(p.left != null){
Q.offer(p.left);
nextCount++;
}
if(p.right != null){
Q.offer(p.right);
nextCount++;
}
}
lists.add(list);
count = nextCount;
}
int length = lists.size();
ArrayList<Integer> temp1 = new ArrayList<Integer>();
ArrayList<Integer> temp2 = new ArrayList<Integer>();
for(int i = 0;i<length/2;i++){
temp1 = lists.get(i);
temp2 = lists.get(length-1-i);
lists.set(i,temp2);
lists.set(length-1-i,temp1);
}
return lists;
}