题目

类型:Stack

难度:简单

二叉树的中序遍历 - 图1

解题思路

1、递归

2、Morris 遍历算法

二叉树的中序遍历 - 图2

代码

  1. package stack;
  2. import common.TreeNode;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class BinaryTreeInorderTraversal {
  6. /**
  7. * 递归
  8. * @param root
  9. * @return
  10. */
  11. public List<Integer> inorderTraversal(TreeNode root) {
  12. List<Integer> res = new ArrayList<>();
  13. inorder(root, res);
  14. return res;
  15. }
  16. public void inorder(TreeNode root, List<Integer> res) {
  17. if (root == null) {
  18. return;
  19. }
  20. inorder(root.left, res);
  21. res.add(root.val);
  22. inorder(root.right, res);
  23. }
  24. /**
  25. * Morris 遍历算法
  26. * @param root
  27. * @return
  28. */
  29. public List<Integer> inorderTraversal2(TreeNode root) {
  30. List<Integer> res = new ArrayList<Integer>();
  31. TreeNode predecessor = null;
  32. while (root != null) {
  33. if (root.left != null) {
  34. // predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
  35. predecessor = root.left;
  36. while (predecessor.right != null && predecessor.right != root) {
  37. predecessor = predecessor.right;
  38. }
  39. // 让 predecessor 的右指针指向 root,继续遍历左子树
  40. if (predecessor.right == null) {
  41. predecessor.right = root;
  42. root = root.left;
  43. }
  44. // 说明左子树已经访问完了,我们需要断开链接
  45. else {
  46. res.add(root.val);
  47. predecessor.right = null;
  48. root = root.right;
  49. }
  50. }
  51. // 如果没有左孩子,则直接访问右孩子
  52. else {
  53. res.add(root.val);
  54. root = root.right;
  55. }
  56. }
  57. return res;
  58. }
  59. }