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 基础上增加了逆序输出,简单的实现可以使用辅助栈或者最后对结果逆序。

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), 使用了队列或者辅助栈作为辅助空间,空间复杂度为 O(n).