1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> round = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode p = queue.poll(); round.add(p.val); if (p.left != null) queue.add(p.left); if (p.right != null) queue.add(p.right); } res.add(round); } return res; }
|