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. C#基础-FileStream

    一.FileStream的基础知识 属性:          CanRead 判断当前流是否支持读取,返回bool值,True表示可以读取          CanWrite 判断当前流是否支持写入, ...

  2. Redis所需内存 超过可用内存怎么办

    爬虫和转载请注明原文地址:博客园蜗牛 http://www.cnblogs.com/tdws/p/5727633.html Redis所需内存 超过可用内存怎么办 Redis修改数据多线程并发—Red ...

  3. 如何在IIS添加MIME扩展类型

    在iis7中默认的MIME类型并不包含所有的后缀名文件,像现在比较热门的apk,ipa文件都是需要手动添加的. 那如何在IIS添加MIME类型?步骤如下: 1.打开iis7,选择你要设置网站,打开mi ...

  4. C#知识点-委托

    一.什么是委托 委托和类一样,是一种用户自定义类型: 类表示的是数据和方法的集合,而委托则持有一个或多个方法: 二.委托的使用 1.声明委托类型 委托是类型,与类一样,委托类型必须在被用来创建变量以及 ...

  5. composer 代码库管理

    composer 代码库管理 参考资料:https://packagist.org/about#naming-your-package简介composer 命令的请求源是 packagist.org* ...

  6. Create function through MySQLdb

    http://stackoverflow.com/questions/745538/create-function-through-mysqldb How can I define a multi-s ...

  7. 【转】mysql_fetch_row , mysql_fetch_array , mysql_fetch_assoc 的区别

    <?php $link = mysql_connect('localhost', 'root', ”); mysql_select_db('abc', $link); $sql = “selec ...

  8. Managing database evolutions

    When you use a relational database, you need a way to track and organize your database schema evolut ...

  9. 彻底解决mysql中文乱码的办法 ???

      MySQL会出现中文乱码的原因不外乎下列几点:1.server本身设定问题,例如还停留在latin12.table的语系设定问题(包含character与collation)3.客户端程式(例如p ...

  10. AMD and CMD are dead之KMDjs内核之分号

    在老版本的kmdjs中,强制了分号的要求.但是总感觉不爽,因为在开发Ket - Kmdjs Extension Tools的时候,总需要导入一些开源的库,然后痛苦就来了,总是报错,一查,就是缺少分号! ...