Binary Tree Postorder Traversal

描述

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

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

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

return [3,2,1].

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

分析

用栈或者Morris遍历。

  1. // Binary Tree Postorder Traversal
  2. // 使用栈,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. vector<int> postorderTraversal(TreeNode *root) {
  6. vector<int> result;
  7. stack<const TreeNode *> s;
  8. /* p,正在访问的结点,q,刚刚访问过的结点*/
  9. const TreeNode *p = root, *q = nullptr;
  10. do {
  11. while (p != nullptr) { /* 往左下走*/
  12. s.push(p);
  13. p = p->left;
  14. }
  15. q = nullptr;
  16. while (!s.empty()) {
  17. p = s.top();
  18. s.pop();
  19. /* 右孩子不存在或已被访问,访问之*/
  20. if (p->right == q) {
  21. result.push_back(p->val);
  22. q = p; /* 保存刚访问过的结点*/
  23. } else {
  24. /* 当前结点不能访问,需第二次进栈*/
  25. s.push(p);
  26. /* 先处理右子树*/
  27. p = p->right;
  28. break;
  29. }
  30. }
  31. } while (!s.empty());
  32. return result;
  33. }
  34. };

Morris后序遍历

  1. // Binary Tree Postorder Traversal
  2. // Morris后序遍历,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. vector postorderTraversal(TreeNode *root) {
  6. vector result;
  7. TreeNode dummy(-1);
  8. TreeNode *cur, *prev = nullptr;
  9. std::function < void(const TreeNode*)> visit =
  10. [&result](const TreeNode *node){
  11. result.push_back(node->val);
  12. };
  13. dummy.left = root;
  14. cur = &dummy;
  15. while (cur != nullptr) {
  16. if (cur->left == nullptr) {
  17. prev = cur; /* 必须要有 */
  18. cur = cur->right;
  19. } else {
  20. TreeNode *node = cur->left;
  21. while (node->right != nullptr && node->right != cur)
  22. node = node->right;
  23. if (node->right == nullptr) { /* 还没线索化,则建立线索 */
  24. node->right = cur;
  25. prev = cur; /* 必须要有 */
  26. cur = cur->left;
  27. } else { /* 已经线索化,则访问节点,并删除线索 */
  28. visit_reverse(cur->left, prev, visit);
  29. prev->right = nullptr;
  30. prev = cur; /* 必须要有 */
  31. cur = cur->right;
  32. }
  33. }
  34. }
  35. return result;
  36. }
  37. private:
  38. // 逆转路径
  39. static void reverse(TreeNode *from, TreeNode *to) {
  40. TreeNode *x = from, *y = from->right, *z;
  41. if (from == to) return;
  42. while (x != to) {
  43. z = y->right;
  44. y->right = x;
  45. x = y;
  46. y = z;
  47. }
  48. }
  49. // 访问逆转后的路径上的所有结点
  50. static void visit_reverse(TreeNode* from, TreeNode *to,
  51. std::function< void(const TreeNode*) >& visit) {
  52. TreeNode *p = to;
  53. reverse(from, to);
  54. while (true) {
  55. visit(p);
  56. if (p == from)
  57. break;
  58. p = p->right;
  59. }
  60. reverse(to, from);
  61. }
  62. };

相关题目

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