LintCode-378,二叉树转双链表
来源:互联网 发布:淘宝怎么看退换货记录 编辑:程序博客网 时间:2024/05/17 22:45
在中序遍历的基础上考虑双链表的串联,中序遍历用递归的手法表现就是:
DoublyListNode dbl1 = bstSupport(root.left); DoublyListNode dbl2 = new DoublyListNode(root.val); DoublyListNode dbl3 = bstSupport(root.right);
随后进行子树串联工作,即当dbl1非空,就进行dbl1到dbl2的串联;dbl3非空,就进行dbl2到dbl3的串联:
if(dbl1!=null){ dbl1.next = dbl2; dbl2.prev = dbl1; } if(dbl3!=null){ dbl2.next = dbl3; dbl3.prev = dbl2; }因为上面这种串联方式,为避免丢失数据,左子树的返回值应该是左子树串联完成后的最后一个节点,右子树的返回值应为右子树串联完成后的第一个节点。
在递归中如何让各子树知道自己是来自左子树还是右子树呢?简单的方法,传入一个参数,这里参数值为1即告诉递归函数,他来自左子树,否则来自右子树。
剩下的就是从中间点开始遍历到链表头尾。
if(flag == 1){ while(dbl2.next!=null){ dbl2 = dbl2.next; } return dbl2;}else{ while(dbl2.prev!=null){ dbl2 = dbl2.prev; } return dbl2;}
终止递归的条件就是传入的参数为空。完整代码:
public class Solution { /** * @param root: The root of tree * @return: the head of doubly list node */ private DoublyListNode bstSupport(TreeNode root,int flag){ if(root!=null){ DoublyListNode dbl1 = bstSupport(root.left,1); DoublyListNode dbl2 = new DoublyListNode(root.val); DoublyListNode dbl3 = bstSupport(root.right,2); if(dbl1!=null){ dbl1.next = dbl2; dbl2.prev = dbl1; } if(dbl3!=null){ dbl2.next = dbl3; dbl3.prev = dbl2; } if(flag == 1){ while(dbl2.next!=null){ dbl2 = dbl2.next; } return dbl2; } else{ while(dbl2.prev!=null){ dbl2 = dbl2.prev; } return dbl2; } } else{ return null; } } public DoublyListNode bstToDoublyList(TreeNode root) { // Write your code here DoublyListNode re = bstSupport(root,1); if(re==null){ return null; } while(re.prev!=null){ re = re.prev; } return re; }}
阅读全文
0 0
- LintCode-378,二叉树转双链表
- LintCode 翻转二叉树
- Lintcode 二叉树前序遍历
- Lintcode 二叉树中序遍历
- LintCode:等价二叉树
- LintCode:平衡二叉树
- LintCode: 将二叉树拆成链表
- lintcode ----等价二叉树
- lintcode ----翻转二叉树
- LintCode:克隆二叉树
- 二叉树路径-lintcode
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode,翻转二叉树
- lintcode-->等价二叉树
- lintcode,克隆二叉树
- 二叉树中序遍历-lintcode
- 平衡二叉树,lintcode
- MFC CComboBox 添加字符串显示不正确的解决方法
- 决策树
- 强制类型转换
- CocoaPods基本配置
- mongodb 操作集合
- LintCode-378,二叉树转双链表
- php 过狗一句话木马的编写
- 数据挖掘python学习——《写给程序员的数据挖掘实践指南》第2章
- R语言:leafletCN的应用
- 准备第一次投稿 SCI 论文,有哪些要注意的地方?
- Fast Power--lintcode
- B. Tell Your World Codeforces Round #431 (Div. 2)(简单模拟)
- Textview部分内容设置颜色、字体、超链接、图片
- 使用Git上传项目代码到Github