二叉树的镜像

一、需求

  • 请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

二、递归法

2.1  思路分析

  1. 若树为空,直接返回null;
  2. 定义两个临时变量leftRoot和rightRoot,分别保存当前结点的左结点和右结点;
  3. 将当前根结点的左结点设置为rightRoot,右结点设置为leftRoot,最后返回root;
  4. 过程就是从下到上、完成右子树的镜像,然后完成左子树的镜像,最后完成根结点的镜像。

2.2  代码实现

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode leftRoot = mirrorTree(root.right);
        TreeNode rightRoot = mirrorTree(root.left);
        root.left = leftRoot;
        root.right = rightRoot;
        return root;
    }
}

2.3  复杂度分析

  • 时间复杂度为O(N),N为二叉树结点的个数,需要遍历所有的结点;
  • 最差情况下,二叉树退化为链表,递归时系统需要O(N)大小的栈空间。

三、辅助栈

3.1  思路分析

  1. 当root为null时,返回null;
  2. 新建辅助栈,并将根结点入栈;
  3. 开始循环,当栈不为空时,弹出结点node,添加node的左、右子结点到栈中,交换node的左右子结点;
  4. 最后返回根结点root。

3.2  代码实现

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(node.left != null) stack.add(node.left);
            if(node.right != null) stack.add(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }
}

3.3  复杂度分析

  • 时间复杂度为O(N),其中N为二叉树的结点数量,建立二叉树镜像需要遍历二叉树的所有结点,占用O(N)的时间;
  • 空间复杂度为O(N),最差情况下,(当为满二叉树时),栈stack最多同时存储(N+1)/2个结点,占用O(N)额外空间。

四、辅助队列

4.1  思路分析

  • 思路与辅助栈的相同,不再赘述,下面提供代码部分。

4.2  代码实现

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(queue.size() != 0) {
            //poll获取失败返回null,remove获取失败抛出异常
            TreeNode node = queue.poll();
            if(node.left != null) queue.add(node.left);
            if(node.right != null) queue.add(node.right);
            //交换当前节点下的左右子节点
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }
}

五、参考地址

作者:Krahets

链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值