Binary Tree Zigzag Level Order Traversal

描述

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:

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

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

return its zigzag level order traversal as:

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

分析

广度优先遍历,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。

递归版

  1. // Binary Tree Zigzag Level Order Traversal
  2. // 递归版,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. vector > zigzagLevelOrder(TreeNode *root) {
  6. vector> result;
  7. traverse(root, 1, result, true);
  8. return result;
  9. }
  10. void traverse(TreeNode *root, size_t level, vector> &result,
  11. bool left_to_right) {
  12. if (!root) return;
  13. if (level > result.size())
  14. result.push_back(vector());
  15. if (left_to_right)
  16. result[level-1].push_back(root->val);
  17. else
  18. result[level-1].insert(result[level-1].begin(), root->val);
  19. traverse(root->left, level+1, result, !left_to_right);
  20. traverse(root->right, level+1, result, !left_to_right);
  21. }
  22. };

迭代版

  1. // Binary Tree Zigzag Level Order Traversal
  2. // 广度优先遍历,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。
  3. // 迭代版,时间复杂度O(n),空间复杂度O(n)
  4. class Solution {
  5. public:
  6. vector > zigzagLevelOrder(TreeNode *root) {
  7. vector > result;
  8. queue current, next;
  9. bool left_to_right = true;
  10. if(root == nullptr) {
  11. return result;
  12. } else {
  13. current.push(root);
  14. }
  15. while (!current.empty()) {
  16. vector level; // elments in one level
  17. while (!current.empty()) {
  18. TreeNode* node = current.front();
  19. current.pop();
  20. level.push_back(node->val);
  21. if (node->left != nullptr) next.push(node->left);
  22. if (node->right != nullptr) next.push(node->right);
  23. }
  24. if (!left_to_right) reverse(level.begin(), level.end());
  25. result.push_back(level);
  26. left_to_right = !left_to_right;
  27. swap(next, current);
  28. }
  29. return result;
  30. }
  31. };

相关题目

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