【LeetCode-0094】二叉树中序遍历,遍历问题的三种解法,难度简单

371 阅读2分钟

原题

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

前序遍历:根左右 中序遍历:左根右 后序遍历:左右根

以下三种解法作以修改可以实现三种遍历!

解法三种

方式一:递归

代码如下:

    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        inorder(root, res);
        return res;
    }
    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {//判空
            return;
        }
        inorder(root.left, res);//递归左节点
        res.add(root.val);//访问当前根节点
        inorder(root.right, res);//递归右节点
    }

方式二:迭代

定义栈Deque,使用LinkedList实现,

  • 将结点左节点全部入栈;
  • 然后出栈最左子节点
  • 读取访问该结点
  • 然后root=root.right访问该结点的右节点
 //迭代
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();//栈
        while (root != null || !stk.isEmpty()) {//root不是null,stk不为空
            while(root!=null){//先将root左节点全部入栈
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();//将最后的结点出栈,读取
            res.add(root.val);
            root = root.right;//遍历右节点
        }
        return res;
    }

方式三:Morris方法

Morris 遍历算法是另一种遍历二叉树的方法,它能将非递归的中序遍历空间复杂度降为 O(1)。

Morris官方步骤:

  • 如果 x无左孩子,先将 x 的值加入答案数组,再访问 x 的右孩子,即x=x.right。
  • 如果 x 有左孩子,则找到 xx左子树上最右的节点(即左子树中序遍历的最后一个节点,x 在中序遍历中的前驱节点),我们记为 predecessor。根据 predecessor 的右孩子是否为空,进行如下操作。
  • 如果 predecessor 的右孩子为空,则将其右孩子指向 x,然后访问 x 的左孩子,即x=x.left。
  • 如果predecessor 的右孩子不为空,则此时其右孩子指向 x,说明我们已经遍历完 x 的左子树,我们将 predecessor 的右孩子置空,将 x 的值加入答案数组,然后访问 x 的右孩子,即 x=x.right。

与前两种不同的是该方法的空间复杂度为1,前两种为n!

理解:假设当前遍历到的节点为 xx,将 xx 的左子树中最右边的节点的右孩子指向 xx,
这样在左子树遍历完成后我们通过这个指向走回了 xx,且能通过这个指向知晓我们已经
遍历完成了左子树,而不用再通过栈来维护,省去了栈的空间复杂度。
    public List<Integer> inorderTraversal3(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        TreeNode predecessor = null;

        while (root != null) {
            if (root.left != null) {
                // predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
                predecessor = root.left;
                while (predecessor.right != null && predecessor.right != root) {
                    predecessor = predecessor.right;
                }

                // 让 predecessor 的右指针指向 root,继续遍历左子树
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                }
                // 说明左子树已经访问完了,我们需要断开链接
                else {
                    res.add(root.val);
                    predecessor.right = null;
                    root = root.right;
                }
            }
            // 如果没有左孩子,则直接访问右孩子
            else {
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }