经典递归做法

  1. public List<Integer> inorderTraversal(TreeNode root) {
  2. ArrayList<Integer> list = new ArrayList<>();
  3. process(root, list);
  4. return list;
  5. }
  6. private void process(TreeNode node, List<Integer> list) {
  7. if (node == null) {
  8. return;
  9. }
  10. process(node.left, list);
  11. list.add(node.val);
  12. process(node.right, list);
  13. }
  14. public class TreeNode {
  15. int val;
  16. TreeNode left;
  17. TreeNode right;
  18. TreeNode() {}
  19. TreeNode(int val) { this.val = val; }
  20. TreeNode(int val, TreeNode left, TreeNode right) {
  21. this.val = val;
  22. this.left = left;
  23. this.right = right;
  24. }
  25. }

迭代做法

  1. public List<Integer> inorderTraversal(TreeNode root) {
  2. List<Integer> ans = new ArrayList<>();
  3. Stack<TreeNode> stack = new Stack<>();
  4. TreeNode cur = root;
  5. while (cur != null || !stack.isEmpty()) {
  6. if (cur != null) {
  7. stack.push(cur);
  8. cur = cur.left;
  9. } else {
  10. cur = stack.pop();
  11. ans.add(cur.val);
  12. cur = cur.right;
  13. }
  14. }
  15. return ans;
  16. }

Morris遍历

  1. public static void morrisIn(Node head) {
  2. if (head == null) {
  3. return;
  4. }
  5. Node cur = head;
  6. Node mostRight = null;
  7. while (cur != null) {
  8. // cur 有没有左树
  9. mostRight = cur.left;
  10. if (mostRight != null) { // 有左树的情况下
  11. // 找到cur左树上,真实的最右
  12. while (mostRight.right != null && mostRight.right != cur) {
  13. mostRight = mostRight.right;
  14. }
  15. // 从while出来, mostRight一定是cur左树上的最右节点
  16. if (mostRight.right == null) {
  17. mostRight.right = cur;
  18. cur = cur.left;
  19. continue;
  20. } else { // mostRight.right --> cur
  21. mostRight.right = null;
  22. System.out.println(cur.value + " ");
  23. }
  24. }
  25. cur = cur.right;
  26. }
  27. }
  28. public static class Node {
  29. public int value;
  30. Node left;
  31. Node right;
  32. public Node(int data) {
  33. this.value = data;
  34. }
  35. }