image.png

思路

层次优先遍历

code

  1. public List<List<Integer>> levelOrderBottom(TreeNode root) {
  2. List<List<Integer>> res = new LinkedList<>();
  3. levelMaker(res, root, 0);
  4. return res;
  5. }
  6. public void levelMaker(List<List<Integer>> list,TreeNode root,int level){
  7. if(root==null)
  8. return;
  9. if(level>=list.size())
  10. list.add(0,new LinkedList<Integer>());
  11. levelMaker(list,root.left,level+1);
  12. levelMaker(list,root.right,level+1);
  13. list.get(list.size()-level-1).add(root.val);
  14. }