class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
//解题思路:DFS遍历,注意结果采用头插法
List<List<Integer>> result = new ArrayList();
dfs(result, root, 0);
return result;
}
private void dfs(List<List<Integer>> result, TreeNode root, int level){
if(root == null){
return;
}
//初始化新的层在第一行
if(level == result.size()){
result.add(0, new ArrayList());
}
//写入结果集;第level层要插入从后往前数的第level层
result.get(result.size() - level - 1).add(root.val);
//左子树
dfs(result, root.left, level + 1);
//右子树
dfs(result, root.right, level + 1);
}
}