问题:输入一颗二叉树,输出它的镜像。
思路:前序遍历二叉树的每个节点,如果遍历到的节点有子节点,就交换它的两个子节点。
/**
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;
}
if(root.left==null && root.right==null){
return;
}
TreeNode temp = null;
temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left!=null){
Mirror(root.left);
}
if(root.right!=null){
Mirror(root.right);
}
}
}