题目

将一个二叉查找树按照中序遍历转换成双向链表

给定一个二叉查找树:

    4
/ \
2 5
/ \
1 3

返回 1<->2<->3<->4<->5

解题

/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Definition for Doubly-ListNode.
* public class DoublyListNode {
* int val;
* DoublyListNode next, prev;
* DoublyListNode(int val) {
* this.val = val;
* this.next = this.prev = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/ public DoublyListNode bstToDoublyList(TreeNode root) {
// Write your code here
if(root == null)
return null;
DoublyListNode Root = new DoublyListNode(root.val);
if(root.left==null && root.right==null){
return Root;
}
DoublyListNode left = bstToDoublyList(root.left);
DoublyListNode tmpLeft = left;
while(tmpLeft!=null && tmpLeft.next!=null){
tmpLeft = tmpLeft.next;
}
if(left!=null){
tmpLeft.next = Root;
Root.prev = tmpLeft;
}
DoublyListNode right = bstToDoublyList(root.right);
if(right!=null){
Root.next = right;
right.prev = Root;
}
return left!=null?left:Root;
}
}

最新文章

  1. Python之路-python(css布局、JavaScript)
  2. WIN32服务程序(三):完整的服务程序实例
  3. response的outputStream输出数据的问题
  4. HTML5里autofocus属性
  5. Java网页数据采集器[续篇-远程操作]【转载】
  6. oracle 之 内存—鞭辟近里(四)
  7. js中的一元加法和一元减法
  8. 三机互ping(自己总结)
  9. R-画图
  10. Python函数分类及操作
  11. 给Mac的Dictionary添加其他原装词典
  12. 《CoderXiaoban团队》第一次作业:团队亮相
  13. 前端知识点总结(HTML)
  14. vue-cli:渲染过程理解2(vue init webpack方式创建)
  15. 集成Javascript Logging on MVC or Core
  16. personal project
  17. Python-JS基础(基础结构~函数)
  18. HDU-6336-构造
  19. cf 557D 二分图黑白染色
  20. 了解vue

热门文章

  1. shell 与用户交互
  2. C#取枚举描述
  3. JAVA类与对象(八)-----重写
  4. C6011 正在取消对 null 指针的引用
  5. ASCII码排序
  6. ORACLE 检查数据库表中是否存在不规范字 段的语句参考.sql
  7. sudo配置临时取得root权限
  8. Java应用程序实现屏幕的&quot;拍照&quot;
  9. [转载]char * 和char []的区别---之第一篇
  10. HDU 5638 拓扑排序+优先队列