二叉树的镜像

来源:互联网 发布:淘宝买同款违法吗 编辑:程序博客网 时间:2024/06/05 17:30

如下有原来的二叉树(左图所示),镜像二叉树(右图所示),通过对比,发现,就是将左右孩子换了个位置而已,其余并没有改变。
思想: 如果当前节点有孩子,则交换位置。否则,返回

镜像过程:

/** * 一棵树得到它的镜像树 前提是有孩子 * @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&&current.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);    } }
0 0
原创粉丝点击