来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

描述

给定一个二叉树,返回它的中序 遍历。

示例:
输入: [1,null,2,3]
1
\
2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

题解

递归法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. List<Integer> list = new ArrayList<>();
  12. public List<Integer> inorderTraversal(TreeNode root) {
  13. if (root == null) {
  14. return list;
  15. }
  16. if (root.left != null) {
  17. inorderTraversal(root.left);
  18. }
  19. list.add(root.val);
  20. if (root.right != null) {
  21. inorderTraversal(root.right);
  22. }
  23. return list;
  24. }
  25. }

复杂度分析

  • 时间复杂度:94. 二叉树的中序遍历(Binary Tree Inorder Traversal) - 图1
  • 空间复杂度:最坏情况下需要空间94. 二叉树的中序遍历(Binary Tree Inorder Traversal) - 图2,平均情况为94. 二叉树的中序遍历(Binary Tree Inorder Traversal) - 图3

    迭代法

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. public List<Integer> inorderTraversal(TreeNode root) {
    12. List<Integer> res = new ArrayList<>();
    13. Stack<TreeNode> stack = new Stack<>();
    14. TreeNode curr = root;
    15. while (null != curr || !stack.isEmpty()) {
    16. while (null != curr) {
    17. stack.push(curr);
    18. curr = curr.left;
    19. }
    20. curr = stack.pop();
    21. res.add(curr.val);
    22. curr = curr.right;
    23. }
    24. return res;
    25. }
    26. }

    复杂度分析

  • 时间复杂度:94. 二叉树的中序遍历(Binary Tree Inorder Traversal) - 图4

  • 空间复杂度:94. 二叉树的中序遍历(Binary Tree Inorder Traversal) - 图5

    参考

  • 一文横扫二叉树的所有遍历方法