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

相关题目

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