image.png

解题思路

递归

image.png

  1. List<List<Integer>> levels = new ArrayList<List<Integer>>();
  2. public void helper(TreeNode node, int level) {
  3. if (levels.size() == level)
  4. levels.add(new ArrayList<Integer>());
  5. // 填充当前层
  6. levels.get(level).add(node.val);
  7. // 处理下一层
  8. if (node.left != null)
  9. helper(node.left, level + 1);
  10. if (node.right != null)
  11. helper(node.right, level + 1);
  12. }
  13. public List<List<Integer>> levelOrder(TreeNode root) {
  14. if (root == null)
  15. return levels;
  16. helper(root, 0);
  17. return levels;
  18. }

迭代

image.png

  1. public List<List<Integer>> levelOrder(TreeNode root) {
  2. List<List<Integer>> levels = new ArrayList<List<Integer>>();
  3. if (root == null) return levels;
  4. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  5. queue.add(root);
  6. int level = 0;
  7. while ( !queue.isEmpty() ) {
  8. // start the current level
  9. levels.add(new ArrayList<Integer>());
  10. // number of elements in the current level
  11. int level_length = queue.size();
  12. for(int i = 0; i < level_length; ++i) {
  13. TreeNode node = queue.remove();
  14. // fulfill the current level
  15. levels.get(level).add(node.val);
  16. // add child nodes of the current level
  17. // in the queue for the next level
  18. if (node.left != null) queue.add(node.left);
  19. if (node.right != null) queue.add(node.right);
  20. }
  21. // go to next level
  22. level++;
  23. }
  24. return levels;
  25. }