剑指offer java版 test18—二叉树镜像

剑指offer java版 test18—二叉树镜像

题目:

操作给定的二叉树,将其变换为源二叉树的镜像。(即左右子树全部对调)
剑指offer java版 test18—二叉树镜像_第1张图片

思路:还是递归

代码:(这次有幸写出和评论区大佬一样的代码,再接再厉)

package cn.test18;

public class test1 {
//测试语句没写,直接牛客网测试的
}

class Solution{
    public void Mirror(TreeNode root){
        if(root!=null){//左右子树交换
            TreeNode tr=null;
            tr=root.left;
            root.left=root.right;
            root.right=tr;

            if(root.left!=null) Mirror(root.left);//接着交换
            if(root.right!=null) Mirror(root.right);//接着交换
        }
    }
}

//结点类
class TreeNode{
    int val=0;
    TreeNode left=null;
    TreeNode right=null;

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

你可能感兴趣的:(剑指offer java版 test18—二叉树镜像)