18、操作给定的二叉树,将其变换为源二叉树的镜像。
思路:将二叉树转换为其镜像,可以看出就是将各个节点的左子树和右子树进行交换,可利用递归的方法进行实现,当前节点不为null时,将其左子树和右子树进行交换。
/**
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 tmp = null;
if(root!=null){
tmp=root.left;
root.left=root.right;
root.right=tmp;
Mirror(root.right);
Mirror(root.left);
}
}
}