【剑指offer】十八,二叉搜索树与双向链表
2015-09-11 15:38
537 查看
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。分析:将二叉搜索树转换成一个排序的双向链表,即在对二叉搜索进行中序遍历时,将节点指向左子树的指针指向中序遍历的前一个节点,将节点指向右子节点的指针指向中序遍历的下一个节点。需要注意的是左子树的最右节点,右子树的最左节点。代码如下:
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { TreeNode tail = null ; public TreeNode Convert(TreeNode pRootOfTree) { convertNode(pRootOfTree); TreeNode head = tail ; while(head!=null&&head.left!=null){ head = head.left; } return head ; } private void convertNode(TreeNode node) { if(node==null){ return ; } TreeNode current = node ; if(current.left!=null){ convertNode(current.left); } current.left = tail ; if(tail!=null){ tail.right=current ; } tail = current ; if(current.right!=null){ convertNode(current.right); } } }
相关文章推荐
- C/S File Transfer Swing
- 如何用javascript获取当前时间戳:
- javascript函数参数
- CSS3 抛物线 加入购物车
- 前端javascript框架之AngularJS学习笔记
- Expect and TCL mini reference manual
- javascript函数参数
- 前端javascript框架之BackboneJS学习笔记
- CSS实现自适应宽度的菜单按钮效果代码
- 【剑指offer】十七,二叉树中和为某一值的路径
- js无缝滚动原理及详解[转自刹那芳华]
- css的flex box布局
- wechat JS-SKD (getLoaction) 定位显示百度map
- jquery 绑定事件 获取方式 --------------data event 获取
- jQuery瀑布流效果
- 《剑指offer》顺时针打印矩阵
- solr查询返回JSON格式
- javascript函数提升
- C/S File Transfer CLI
- JS 去字符串空格