分析一下镜像的过程,即交换左右子树,也就是Mirror(root.left)和Mirror(root.right)。然后写出交换规则和终止条件即可。
/**
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) {
TreeNode temp=new TreeNode(0);
if(root==null){//终止条件
return;
}
temp=root.left;
root.left=root.right; //三行交换规则
root.right=temp;
Mirror(root.left); //镜像左子树
Mirror(root.right);//镜像右子树
}
}