题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:
根结点不变,左右子结点交换位置,每一次都是这样操作,就可以利用递归实现。
// 二叉树的镜像
public class Solution {
class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
TreeNode(int x) {
val = x;
}
}
public void Mirror(TreeNode root) {
if ((root == null) || (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);
}
}
}