剑指Offer(十八)二叉树的镜像(Java版 )

一、题目描述

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

二、代码分析

/**
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 = null;
        //完成左右交换
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        if( root.left != null ) Mirror(root.left);
        if( root.right != null ) Mirror(root.right);
    }
}        

三、运行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41835916/article/details/80688188
今日推荐