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 List<Integer> inorderTraversal(TreeNode root) {
  5. ArrayList<Integer> result = new ArrayList<>();
  6. Stack<TreeNode> s = new Stack<>();
  7. TreeNode p = root;
  8. while (!s.empty() || p != null) {
  9. if (p != null) {
  10. s.push(p);
  11. p = p.left;
  12. } else {
  13. p = s.pop();
  14. result.add(p.val);
  15. p = p.right;
  16. }
  17. }
  18. return result;
  19. }
  20. }

Morris中序遍历

  1. // Binary Tree Inorder Traversal
  2. // Morris中序遍历,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public List inorderTraversal(TreeNode root) {
  5. ArrayList result = new ArrayList<>();
  6. TreeNode cur = root;
  7. TreeNode prev = null;
  8. while (cur != null) {
  9. if (cur.left == null) {
  10. result.add(cur.val);
  11. prev = cur;
  12. cur = cur.right;
  13. } else {
  14. /* 查找前驱 */
  15. TreeNode node = cur.left;
  16. while (node.right != null && node.right != cur)
  17. node = node.right;
  18. if (node.right == null) { /* 还没线索化,则建立线索 */
  19. node.right = cur;
  20. /* prev = cur; 不能有这句,cur还没有被访问 */
  21. cur = cur.left;
  22. } else { /* 已经线索化,则访问节点,并删除线索 */
  23. result.add(cur.val);
  24. node.right = null;
  25. prev = cur;
  26. cur = cur.right;
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32. }

相关题目

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