二叉树的镜像问题(剑指Offer)

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

/**
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;
        TreeNode tmp = null;
        tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        if(root.left != null){
            Mirror(root.left);
        }
        if(root.right != null){
            Mirror(root.right);
        }
    }
}

当根节点为空的时候直接return。
如果不为空,利用中间变量tmp,来进行根节点的左子节点和右子节点的值交换。
如果根节点的左子节点不为空,递归调用Mirror方法,参数为root.left;
如果根节点的右子节点不为空,递归调用Mirror方法,参数为root.right;

猜你喜欢

转载自blog.csdn.net/DIDI___/article/details/104082983