- 题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。 - 输入描述:
- 分析:
可以发现,当传进去的root不为null时,就将root的左右节点交换,6和10交换后他们各自的子节点也跟着换了位置,只要将每个节点的左右子节点都交换就可以发现所有的对称节点都交换了位置。
代码:
/**
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){
TreeNode temp;
temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left != null){
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}
}
}