按照层次从树的底部遍历到树的顶部,也就是层次遍历之后将遍历的位置两两对调
<span style="font-size:18px;">/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
static ArrayList<ArrayList<Integer>> ans;
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ans = new ArrayList<ArrayList<Integer>>();
func(root, 0);
int len = ans.size();
for(int i = 0; i < len / 2; ++i){
Object o = (Object)ans.get(i);
ans.set(i, ans.get(len - i - 1));
ans.set(len - i - 1, (ArrayList<Integer>)(o));
}
return ans;
}
public static void func(TreeNode node, int cur){
if(node != null){
if(ans.size() <= cur)
ans.add(new ArrayList<Integer>());
ans.get(cur).add(node.val);
func(node.left, cur + 1);
func(node.right, cur + 1);
}
}
}</span>