Binary Tree Level Order Traversal II

描述

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

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

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

return its bottom-up level order traversal as:

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

分析

在上一题 Binary Tree Level Order Traversal 的基础上,reverse()一下即可。

递归版

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

迭代版

  1. // Binary Tree Level Order Traversal II
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. public class Solution {
  4. public List<List<Integer>> levelOrderBottom(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. Collections.reverse(result);
  28. return result;
  29. }
  30. }

相关题目

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