您的位置:首页 > 其它

二叉树的镜像

2016-09-26 07:35 232 查看
如下有原来的二叉树(左图所示),镜像二叉树(右图所示),通过对比,发现,就是将左右孩子换了个位置而已,其余并没有改变。

思想: 如果当前节点有孩子,则交换位置。否则,返回



镜像过程:



/**
* 一棵树得到它的镜像树 前提是有孩子
* @author BayMax
*
*/
class TreeNode{
TreeNode left;
TreeNode right;
int value;
public TreeNode(int value) {

this.value=value;
this.left=null;
this.right=null;
}

}
public class MirrorTree {
public void transMirrorTree(TreeNode root){
//边界条件 左右孩子为空 二叉树为空
if(root==null)
return;
//如果存在孩子则交换位置 交换位置即可 不需要考虑只存在左孩子或者右孩子的问题,初始化的时候每个孩子都为null,如果没有右孩子,那么左孩子一样会与右孩子(null)交换位置,即左孩子变成右孩子,右孩子变为左孩子(为空null)
TreeNode current = root;
//需要一个节点作为交换
TreeNode temp = null;
if(current.left==null&¤t.right==null)
return;

else{
temp = current.left;
current.left=current.right;
current.right=temp;
}
if(current.left!=null)
transMirrorTree(current.left);//递归
if(current.right!=null)
transMirrorTree(current.right);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 镜像