18 图解剑指Offer 二叉树的镜像 Java题解

18 图解剑指Offer 二叉树的镜像 Java题解

题目链接

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。
在这里插入图片描述

题解:

1.当二叉树根节点为null,或没有叶子节点的时候直接return;
2. 创建一个temp临时节点,二叉树左右节点交换。
3.如果root.left != null root.left = Mirror(root.left)
4.如果root.right!= null root.right= Mirror(root.right)
5.树的问题一般可以用子树递归的思想解决

图解:

在这里插入图片描述

代码:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    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;
        //递归交换叶子节点
        if(root.left != null)
            Mirror(root.left);
        if(root.right != null)
            Mirror(root.right);
    }
}

复杂度

空间复杂度: 空间复杂度为O(1)
最坏时间复杂度: 递归时间复杂度O( logn)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章