Binary Tree Level Order Traversal

描述

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:Given binary tree {3,9,20,#,#,15,7},

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its level order traversal as:

  1. [
  2. [3],
  3. [9,20],
  4. [15,7]
  5. ]

分析

递归版

  1. // Binary Tree Level Order Traversal
  2. // 递归版,时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public List<List<Integer>> levelOrder(TreeNode root) {
  5. List<List<Integer>> result = new ArrayList<>();
  6. traverse(root, 1, result);
  7. return result;
  8. }
  9. void traverse(TreeNode root, int level,
  10. List<List<Integer>> result) {
  11. if (root == null) return;
  12. if (level > result.size())
  13. result.add(new ArrayList<>());
  14. result.get(level-1).add(root.val);
  15. traverse(root.left, level+1, result);
  16. traverse(root.right, level+1, result);
  17. }
  18. }

迭代版

  1. // Binary Tree Level Order Traversal
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. public class Solution {
  4. public List<List<Integer>> levelOrder(TreeNode root) {
  5. List<List<Integer>> result = new ArrayList<>();
  6. Queue<TreeNode> current = new LinkedList<>();
  7. Queue<TreeNode> next = new LinkedList<>();
  8. if(root == null) {
  9. return result;
  10. } else {
  11. current.offer(root);
  12. }
  13. while (!current.isEmpty()) {
  14. ArrayList<Integer> level = new ArrayList<>(); // elments in one level
  15. while (!current.isEmpty()) {
  16. TreeNode node = current.poll();
  17. level.add(node.val);
  18. if (node.left != null) next.add(node.left);
  19. if (node.right != null) next.add(node.right);
  20. }
  21. result.add(level);
  22. // swap
  23. Queue<TreeNode> tmp = current;
  24. current = next;
  25. next = tmp;
  26. }
  27. return result;
  28. }
  29. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/traversal/binary-tree-level-order-traversal.html