正常做bfs,然后List添加的时候,从头部开始添加add(0, ...)
class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while(!q.isEmpty()){ int size = q.size(); List<Integer> level = new ArrayList<>(); for(int i=0; i<size; i++){ TreeNode cur = q.poll(); if(cur == null) continue; level.add(cur.val); q.offer(cur.left); q.offer(cur.right); } if(!level.isEmpty()) res.add(0, level); } return res; } }