https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
bfs求解,和普通的层次遍历差不多,直接从头插入就可以了
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> list = new LinkedList<>(); if (root == null) { return list; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> cur = new LinkedList<>(); for (int i = queue.size(); i > 0; i--) { TreeNode node = queue.poll(); cur.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } list.add(0, cur); } return list; } }