Binary Tree Level Order Traversal II

Question

  1. Given a binary tree, return the bottom-up level order traversal of its nodes' values.
  2. (ie, from left to right, level by level from leaf to root).
  3. Example
  4. Given binary tree {3,9,20,#,#,15,7},
  5. 3
  6. / \
  7. 9 20
  8. / \
  9. 15 7
  10. return its bottom-up level order traversal as:
  11. [
  12. [15,7],
  13. [9,20],
  14. [3]
  15. ]

題解

這題在普通的 BFS 基礎上增加了逆序輸出,簡單的實現可以使用 Stack 或者最後對結果逆序。

Java - Stack

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param root: The root of binary tree.
  15. * @return: buttom-up level order a list of lists of integer
  16. */
  17. public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
  18. ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
  19. if (root == null) return result;
  20. Stack<ArrayList<Integer>> s = new Stack<ArrayList<Integer>>();
  21. Queue<TreeNode> q = new LinkedList<TreeNode>();
  22. q.offer(root);
  23. while (!q.isEmpty()) {
  24. int qLen = q.size();
  25. ArrayList<Integer> aList = new ArrayList<Integer>();
  26. for (int i = 0; i < qLen; i++) {
  27. TreeNode node = q.poll();
  28. aList.add(node.val);
  29. if (node.left != null) q.offer(node.left);
  30. if (node.right != null) q.offer(node.right);
  31. }
  32. s.push(aList);
  33. }
  34. while (!s.empty()) {
  35. result.add(s.pop());
  36. }
  37. return result;
  38. }
  39. }

Java - Reverse

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param root: The root of binary tree.
  15. * @return: buttom-up level order a list of lists of integer
  16. */
  17. public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
  18. ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
  19. if (root == null) return result;
  20. Queue<TreeNode> q = new LinkedList<TreeNode>();
  21. q.offer(root);
  22. while (!q.isEmpty()) {
  23. int qLen = q.size();
  24. ArrayList<Integer> aList = new ArrayList<Integer>();
  25. for (int i = 0; i < qLen; i++) {
  26. TreeNode node = q.poll();
  27. aList.add(node.val);
  28. if (node.left != null) q.offer(node.left);
  29. if (node.right != null) q.offer(node.right);
  30. }
  31. result.add(aList);
  32. }
  33. Collections.reverse(result);
  34. return result;
  35. }
  36. }

源碼分析

Java 中 Queue 是接口,通常可用 LinkedList 實例化。

複雜度分析

時間複雜度爲 O(n), 使用了 Queue 或者 Stack 作爲輔助空間,空間複雜度爲 O(n).