二叉树的镜像
来源:互联网 发布:淘宝买同款违法吗 编辑:程序博客网 时间: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&¤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); } }
0 0
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 小话设计模式(六)适配器模式
- AR或许会带来新的网络隐患 最明智的是未雨绸缪
- Android数据篇—SharedPreferences
- XListView下拉刷新上拉加载
- 第26周-window程序设计(基础篇)-第5章(图形基础)-取得设备内容的多方法
- 二叉树的镜像
- Fragment+ViewPager+Button
- XML解析之pull
- 微信小程序把玩(十六)form组件
- jquery多选获取其选中的值
- 代码里写控件的一些例子
- 6个常见的 PHP 安全性攻击
- JavaScript的数据类型和命名规则
- 单例模式(懒汉模式)