尝试一
结果:成功
代码:
/**
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;
}
//临时存储left。便于交换
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
Mirror(root.left);
Mirror(root.right);
}
}
分析:
我们对两个二叉树进行中序遍历:
分别为:
5,6,7,8,9,10,11
11,10,9,8,7,6,5
刚好是以根节点为界限,交换左右(至于节点个数为偶数,稍有不同,不分析了)。这只是我注意到的一个特定。然而本题可以不用。
重点来了:
上面两颗二叉树,刚好是左右节点交换。然后递归下去。
结论
- 二叉树先序遍历。先根节点,然后左子树,右子树。