题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解题思路分析
这是一个很明显的递归题,直接上代码,很容易懂
代码实现
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);
}
}