Binary Tree Inorder Traversal

描述

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

For example:

Given binary tree {1,#,2,3},

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

return [1,3,2].

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

分析

用栈或者Morris遍历。

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

Morris中序遍历

  1. // Binary Tree Inorder Traversal
  2. // Morris中序遍历,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. vector inorderTraversal(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;
  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. node->right = cur;
  20. /* prev = cur; 不能有这句,cur还没有被访问 */
  21. cur = cur->left;
  22. } else { /* 已经线索化,则访问节点,并删除线索 */
  23. result.push_back(cur->val);
  24. node->right = nullptr;
  25. prev = 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-inorder-traversal.html