Binary Tree Preorder Traversal

描述

Given a binary tree, return the preorder traversal of its nodes' values.

For example:Given binary tree {1,#,2,3},

  1. 1
  2. \
  3. 2
  4. /
  5. 3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

分析

用栈或者Morris遍历。

  1. // Binary Tree Preorder Traversal
  2. // 使用栈,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. vector<int> preorderTraversal(TreeNode *root) {
  6. vector<int> result;
  7. stack<const TreeNode *> s;
  8. if (root != nullptr) s.push(root);
  9. while (!s.empty()) {
  10. const TreeNode *p = s.top();
  11. s.pop();
  12. result.push_back(p->val);
  13. if (p->right != nullptr) s.push(p->right);
  14. if (p->left != nullptr) s.push(p->left);
  15. }
  16. return result;
  17. }
  18. };

Morris先序遍历

  1. // Binary Tree Preorder Traversal
  2. // Morris先序遍历,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. vector preorderTraversal(TreeNode *root) {
  6. vector result;
  7. TreeNode *cur = root, *prev = nullptr;
  8. while (cur != nullptr) {
  9. if (cur->left == nullptr) {
  10. result.push_back(cur->val);
  11. prev = cur; /* cur刚刚被访问过 */
  12. cur = cur->right;
  13. } else {
  14. /* 查找前驱 */
  15. TreeNode *node = cur->left;
  16. while (node->right != nullptr && node->right != cur)
  17. node = node->right;
  18. if (node->right == nullptr) { /* 还没线索化,则建立线索 */
  19. result.push_back(cur->val); /* 仅这一行的位置与中序不同 */
  20. node->right = cur;
  21. prev = cur; /* cur刚刚被访问过 */
  22. cur = cur->left;
  23. } else { /* 已经线索化,则删除线索 */
  24. node->right = nullptr;
  25. /* prev = cur; 不能有这句,cur已经被访问 */
  26. cur = cur->right;
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32. };

相关题目

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