美文网首页
【剑指27】二叉树的镜像

【剑指27】二叉树的镜像

作者: 浅浅星空 | 来源:发表于2019-07-20 21:38 被阅读0次

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述

image.png

分析

1.递归

   //1.递归
    public void Mirror(TreeNode root) {
        if (root == null) return;
        if (root.left == null && root.right == null) return;
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        Mirror(root.left);
        Mirror(root.right);

    }

2.非递归

    //2.非递归
    public void Mirror(TreeNode root) {
        if (root == null) return;
        if (root.left == null && root.right == null) return;
        Stack<TreeNode> stack = new Stack();
        while (true) {
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;

            if (root.right != null) {
                stack.push(root.right);
            }
            if (root.left != null) {
                root = root.left;
            } else {
                if (stack.empty()) break;
                root = stack.pop();
            }
        }

    }

相关文章

网友评论

      本文标题:【剑指27】二叉树的镜像

      本文链接:https://www.haomeiwen.com/subject/mexplctx.html