操作给定的二叉树,将其变换为源二叉树的镜像
/**
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 = root.left;
root.left = root.right;
root.right = temp;
if (root.left != null) {
Mirror(root.left);
}
if (root.right != null) {
Mirror(root.right);
}
}
}