二叉树的镜像 代码 思路 坑 More

操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/
6 10
/ /
5 7 9 11
镜像二叉树
8
/
10 6
/ /
11 9 7 5

代码

1
2
3
4
5
6
7
8
9
10
11

public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class  {
public void Mirror(TreeNode pRoot) {
Mirror2(root);
}

public void Mirror2(TreeNode t){
TreeNode temp = null;
if(t != null){
temp = t.left;
t.left = t.right;
t.right = temp;
Mirror2(t.left);
Mirror2(t.right);
}
}

思路

将左右两个子树交换,递归的调用

1 开始的时候将Mirror2(t.left),Mirror2(t.right)写在了外面,这样的话,会报空,因为if走完后,接着走这两条。

More

感觉人生第一次用递归一次写完这个题目,并提交成功,吼开心。。。。。