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

Top down 的解题方法:

1. 将LinkedList的值保存到一个数组中,转化成Convert Sorted Array to Binary Search Tree 来解决

时间复杂度为O(n), 空间复杂度为O(n)

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null){
return null;
}
int len = 0;
ListNode p = head;
while(p != null){
len ++;
p = p.next;
}
int[] num = new int[len];
p = head;
int i = 0;
while(p != null){
num[i++] = p.val;
p = p.next;
} return generate(num, 0, len - 1);
} public TreeNode generate(int[] num, int start, int end){
if(start > end){
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(num[mid]);
root.left = generate(num, start, mid - 1);
root.right = generate(num, mid + 1, end);
return root;
}
}

2. 使用上题的解题思路:

遍历链表,找到中间元素,将该元素作为根节点时间复杂度为O(NlgN)

因为每层的递归调用需要遍历N/2个元素,而一共有lgN层

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null){
return null;
}
int len = 0;
ListNode p = head;
while(p != null){
len ++;
p = p.next;
}
return generate(head, len);
} public TreeNode generate(ListNode head, int N){
if(N <= 0){
return null;
}
int mid = (1 + N) / 2;
ListNode p = head;
int tmp = mid - 1;
while(tmp > 0){
p = p.next;
tmp --;
}
TreeNode root = new TreeNode(p.val);
root.left = generate(head, mid - 1);
root.right = generate(p.next, N - mid);
return root;
} }

Best Solution:
As usual, the best solution requires you to think from another perspective. In other words, we no longer create nodes in the tree using the top-down approach. We create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order while creating nodes.

Isn’t the bottom-up approach neat? Each time you are stucked with the top-down approach, give bottom-up a try. Although bottom-up approach is not the most natural way we think, it is extremely helpful in some cases. However, you should prefer top-down instead of bottom-up in general, since the latter is more difficult to verify in correctness.

Below is the code for converting a singly linked list to a balanced BST. Please note that the algorithm requires the list’s length to be passed in as the function’s parameters. The list’s length could be found in O(N) time by traversing the entire list’s once. The recursive calls traverse the list and create tree’s nodes by the list’s order, which also takes O(N) time. Therefore, the overall run time complexity is still O(N).

 BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
if (start > end) return NULL;
// same as (start+end)/2, avoids overflow
int mid = start + (end - start) / ;
BinaryTree *leftChild = sortedListToBST(list, start, mid-);
BinaryTree *parent = new BinaryTree(list->data);
parent->left = leftChild;
list = list->next;
parent->right = sortedListToBST(list, mid+, end);
return parent;
} BinaryTree* sortedListToBST(ListNode *head, int n) {
return sortedListToBST(head, , n-);
}

leetcode -- Convert Sorted List to Binary Search Tree的更多相关文章

  1. LeetCode:Convert Sorted Array to Binary Search Tree,Convert Sorted List to Binary Search Tree

    LeetCode:Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in asce ...

  2. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  3. [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树

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

  4. [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 这道 ...

  5. LeetCode: Convert Sorted List to Binary Search Tree 解题报告

    Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in as ...

  6. LeetCode: Convert Sorted Array to Binary Search Tree 解题报告

    Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending ord ...

  7. LeetCode——Convert Sorted List to Binary Search Tree

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

  8. [LeetCode] Convert Sorted List to Binary Search Tree DFS,深度搜索

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

  9. LeetCode——Convert Sorted Array to Binary Search Tree

    Description: Given an array where elements are sorted in ascending order, convert it to a height bal ...

随机推荐

  1. 不使用jQuery对Web API接口POST,PUT,DELETE数据

    前些天,Insus.NET有演示Web API接口的操作: <怎样操作WebAPI接口(显示数据)>http://www.cnblogs.com/insus/p/5670401.html ...

  2. Linux命令详解之—tail命令

    tail命令也是一个非常常用的文件查看类的命令,今天就为大家介绍下Linux tail命令的用法. 更多Linux命令详情请看:Linux命令速查手册 Linux tail命令主要用来从指定点开始将文 ...

  3. SpringMvc面试题

    f-sm-1. 讲下SpringMvc和Struts1,Struts2的比较的优势 性能上Struts1>SpringMvc>Struts2 开发速度上SpringMvc和Struts2差 ...

  4. CentOS操作记录

    基本操作记录 1.centos已经进到图形界面后怎么打开命令行:ctrl+alt+F3 得到如下命令界面 用用户名和密码登录 切换回图形界面时输入的命令:ctrl+alt+F1 2.重新启动系统:#r ...

  5. JAVA中常说的三大框架指:SSH

    即:spring.Struts.hibernate Spring:功能强大的组件粘合济,能够将你的所有的Java功能模块用配置文件的方式组合起来(还让你感觉不到spring的存在)成为一个完成的应用 ...

  6. Tomcat源代码-门面模式(Facade)

    从Tomcat源码提炼出设计模式-门面设计模式: 概念 外部访问内部,耦合度增加,不利于扩展.而门面模式在内部基础上进行再度封装,只提供外部想要的方法.这时访问方式由“外部---内部”变为了“外部-- ...

  7. JQ常用代码

    页面加载的时候添加一个定时器,0秒之后执行hideURLbar函数. hideURLbar函数将页面滚动至坐标(0,1) <script type="application/x-jav ...

  8. jQuery切换网页皮肤保存到Cookie实例

    效果体验:http://keleyi.com/keleyi/phtml/jqtexiao/25.htm 以下是源代码: <!DOCTYPE html PUBLIC "-//W3C//D ...

  9. MySQL基础(非常全)

    MySQL基础 一.MySQL概述 1.什么是数据库 ? 答:数据的仓库,如:在ATM的示例中我们创建了一个 db 目录,称其为数据库 2.什么是 MySQL.Oracle.SQLite.Access ...

  10. Git常用命令总结

    Git常用命令总结 git init      在本地新建一个repo,进入一个项目目录,执行git init,会初始化一个repo,并在当前文件夹下创建一个.git文件夹.   git clone ...