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. class Solution {
  4. public:
  5. vector<vector<int> > levelOrderBottom(TreeNode *root) {
  6. vector<vector<int>> result;
  7. traverse(root, 1, result);
  8. std::reverse(result.begin(), result.end()); // 比上一题多此一行
  9. return result;
  10. }
  11. void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
  12. if (!root) return;
  13. if (level > result.size())
  14. result.push_back(vector<int>());
  15. result[level-1].push_back(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. class Solution {
  4. public:
  5. vector<vector<int> > levelOrderBottom(TreeNode *root) {
  6. vector<vector<int> > result;
  7. if(root == nullptr) return result;
  8. queue<TreeNode*> current, next;
  9. vector<int> level; // elments in level level
  10. current.push(root);
  11. while (!current.empty()) {
  12. while (!current.empty()) {
  13. TreeNode* node = current.front();
  14. current.pop();
  15. level.push_back(node->val);
  16. if (node->left != nullptr) next.push(node->left);
  17. if (node->right != nullptr) next.push(node->right);
  18. }
  19. result.push_back(level);
  20. level.clear();
  21. swap(next, current);
  22. }
  23. reverse(result.begin(), result.end()); // 比上一题多此一行
  24. return result;
  25. }
  26. };

相关题目

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