剑指 27. 二叉树的镜像 - 难度简单

1. 题目描述

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

例如输入:
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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof

2. 题解

1、我的提交

使用自底向上的递归,并且先遍历右子树,再遍历左子树。

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return root;
        }
        helper(root);
        return root;
    }

    //自底向上的遍历
    private void helper(TreeNode root){
        if(root == null){
            return;
        }
        //右
        helper(root.right);
        //左
        helper(root.left);
        //左右交换
        TreeNode temp = new TreeNode(0);
        if(root.left != null){
            temp = root.left;
            if(root.right != null){
                // left!=null, right!=null
                root.left = root.right;
                root.right = temp; 
            }else{
                // left!=null, right==null
                root.right = temp;
                root.left = null;
            }
        }else{
            if(root.right != null){
                // left==null, right!=null
                root.left = root.right;
                root.right = null; 
            }
        }
    }
}

时间复杂度:O(n),全部节点需要遍历一遍
空间复杂度:O(n),当树退化为链表时需要栈空间O(n)。

2、更简洁的递归代码

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode temp = root.left;
        //遍历右,作为左节点返回
        root.left = mirrorTree(root.right);
        //遍历左,作为右节点返回
        root.right = mirrorTree(temp);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值