剑指offer-面试题27:二叉树的镜像

题目描述

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

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

镜像输出:

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

示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000

方法一(递归)

1.解题思路

这题的思路很简单,就是将每一个节点的左右子节点交换顺序,然后左右子树也进行相同的操作,当没有节点时,递归终止。

2.代码实现
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return root;
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}
3.复杂度分析
  • 时间复杂度:需要遍历整颗二叉树,所以时间复杂度为O(n)
  • 空间复杂度:递归栈的深度为树中节点个数,所以空间复杂度为O(n)

方法二(队列)

1.解题思路

通过队列进行层序遍历,遍历的过程中,将每个节点的左右子节点交换顺序。

2.代码实现
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return root;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.poll();
            TreeNode temp=node.left;
            node.left=node.right;
            node.right=temp;
            if(node.left!=null){
                queue.offer(node.left);
            }
            if(node.right!=null){
                queue.offer(node.right);
            }
        }
        return root;
    }
}
3.复杂度分析
  • 时间复杂度:需要遍历整颗二叉树,所以时间复杂度为O(n)
  • 空间复杂度:需要额外容量为n的队列,所以空间复杂度为O(n)

方法三(栈)

1.解题思路

通过栈进行前序遍历,遍历的过程中,将每个节点的左右子节点交换顺序。

2.代码实现
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return root;
        Deque<TreeNode> stack=new LinkedList<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node=stack.pop();
            TreeNode temp=node.left;
            node.left=node.right;
            node.right=temp;
            if(node.right!=null){
                stack.push(node.right);
            }
            if(node.left!=null){
                stack.push(node.left);
            }
        }
        return root;
    }
}
3.复杂度分析
  • 时间复杂度:需要遍历整颗二叉树,所以时间复杂度为O(n)
  • 空间复杂度:需要额外容量为n的栈,所以空间复杂度为O(n)

剑指offer全集入口: 请戳这里

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值