Question:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
/ \
-3 9
/ /
-10 5

Tips:

给定一个有序的单链表,将其转换成一个平衡二叉查找树。

思路:

(1)找到链表的中间位置,作为BST的根节点。方法就是设置两个指针,fast、slow,slow每次走一步,fast每次走两步。当fast先遇到null,slow就指向链表中间节点。

(2)左、右子树的根节点也用相同的方法找到,并作为根节点的左右子树。接下来的结点可用递归来解决。

代码:

public TreeNode sortedListToBST(ListNode head){
if(head==null) return null;
return toBST(head,null);
} private TreeNode toBST(ListNode head,ListNode tail) {
if(head==tail) return null;
ListNode fast=head;
ListNode slow=head;
//循环找到链表中间位置作为根节点。
while(fast!=tail && fast.next!=tail){
slow=slow.next;
fast=fast.next.next;
}
TreeNode root=new TreeNode(slow.val);
root.left=toBST(head,slow);
root.right=toBST(slow.next,tail);
return root;
}

最新文章

  1. shortcuts on Windows and MacOS
  2. 其实今天没有欲望..-MySQLi
  3. 北京程序员 VS 硅谷程序员(转)
  4. Android学习笔记(第二篇)View中的五大布局
  5. Escape Sequences
  6. 标签栏控制器(UITabBarController)
  7. python笔记1
  8. Ubuntu 14.04 Android 使用Maven二 创建自己的Mavenproject
  9. C#- 泛型去除重复项
  10. Color the ball----HDOJ1556
  11. 无限循环的ViewPager
  12. 泛型 "new的性能"
  13. C++高效安全的运行时动态类型转换
  14. android之.9.png详解
  15. HBase压缩
  16. 【转】利用apktool反编译apk,并且重新签名打包
  17. Unicode String to a UTF-8 TypedArray Buffer in JavaScript
  18. 【从0到1学Web前端】CSS定位问题三(相对定位,绝对定位) 分类: HTML+CSS 2015-05-29 23:01 842人阅读 评论(0) 收藏
  19. python开发_webbrowser_浏览器控制模块
  20. Android问题集锦之三十四:android studio导入项目下载gradle-x.x.x-all.zip

热门文章

  1. PostgreSQL参数学习:deadlock_timeout
  2. 一个java程序员该具备的工具
  3. 项目中 Spring 配置文件的选型问题 (xml和注解的抉择)
  4. SQL语句汇总(一)——数据库与表的操作以及创建约束
  5. 正则表达式30min
  6. OpenGL 笔记<1> 固定管线实例 + 双缓存测试实例
  7. 如何批量删除QQ浏览器指定历史记录和导出指定的历史记录
  8. 小刘的深度学习---Faster RCNN
  9. stat命令详解
  10. ajax 异步刷新