swordpointtooffer(19): 二叉树的镜像 分析 实现

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

分析

从上往下递归交换左右子树。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class {
class TreeNode{
int value;
TreeNode left;
TreeNode right;
}
public void mirror(TreeNode root) {
if(root == null){
return;
}
if(root.left == null && root.right == null){
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null){
mirror(root.left);
}
if(root.right != null){
mirror(root.right);
}
}
}