二叉树的镜像
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); } }
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- 虚拟化基础架构Windows 2008篇之6-启动Windows部署服务
- 微软镜像下载
- 简述SQL Server 2005数据库镜像相关知识
- SQL Server 2005 镜像构建手册(sql2005数据库同步镜像方案)
- SQL Server误区30日谈 第7天 一个实例多个镜像和日志传送延迟
- SQL Server中避免触发镜像SUSPEND的N种方法
- SQLServer 镜像功能完全实现
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- 图片旋转、鼠标滚轮缩放、镜像、切换图片js代码
- 使用RSYNC在服务器间镜像或者备份目录和文件
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例