LeetCode 热题 HOT 100 Java题解——94. 二叉树的中序遍历

94. 二叉树的中序遍历

题目:

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

示例:

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

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

迭代中序遍历

迭代的思想就是构造一个栈,模拟递归的操作,遍历左边的时候,把一路上的节点存入栈,左边到头后,从栈中取出,加入结果集合后再遍历右边。

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}
复杂度分析
  • 时间复杂度: O ( n ) O(n) O(n)

    每个节点被访问一次。

  • 空间复杂度: O ( n ) O(n) O(n)

    最差情况下递归栈大小 O ( n ) O(n) O(n)

Morris中序遍历

Morris 遍历算法整体步骤如下(假设当前遍历到的节点为 x):

  1. 如果 x x x 无左孩子,先将 x x x 的值加入答案数组,再访问 x x x 的右孩子,即 x = x . r i g h t x=x.right x=x.right
  2. 如果 x x x 有左孩子,则找到 x x x 左子树上最右的节点(即左子树中序遍历的最后一个节点, x x x 在中序遍历中的前驱节点),我们记为 p r e d e c e s s o r predecessor predecessor。根据 p r e d e c e s s o r predecessor predecessor 的右孩子是否为空,进行如下操作。
    1. 如果 p r e d e c e s s o r predecessor predecessor 的右孩子为空,则将其右孩子指向 xx,然后访问 x x x 的左孩子,即 x = x . l e f t x=x.left x=x.left
    2. 如果 p r e d e c e s s o r predecessor predecessor 的右孩子不为空,则此时其右孩子指向 x x x,说明我们已经遍历完 x x x 的左子树,我们将 p r e d e c e s s o r predecessor predecessor 的右孩子置空,将 x x x 的值加入答案数组,然后访问 x x x 的右孩子,即 x = x . r i g h t x=x.right x=x.right
  3. 重复上述操作,直至访问完整棵树。
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        while(root != null) {
            if (root.left == null) {
                res.add(root.val);
                root = root.right;
            }
            else {
                TreeNode predecessor = root.left;
                while(predecessor.right != null && predecessor.right != root) predecessor = predecessor.right;
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                }else {
                    res.add(root.val);
                    predecessor.right = null;
                    root = root.right;
                }

            }
        }
        return res;
    }
}

复杂度分析
  • 时间复杂度: O ( n ) O(n) O(n)

    每个节点被访问一次。

  • 空间复杂度: O ( 1 ) O(1) O(1)

    利用二叉树中的空指针,不需要额外空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值