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. B/S工作原理

    B/S疑问 先对比C/S,在C/S中我们开发时怎么做的,是不是这样:拖控件,写方法,所有的功能基本就是这样,就像我们的机房收费系统,C/S学习完之后,我们开始B/S学习,这里我们接触的是ASP.NET ...

  2. java数据类型

    对String来说,”==“是用来判断两个字符串(对象)的地址是否相同,即判断是否是同一个字符串的应用.”equals()“则是判断两个字符串(对象)的值是否相等,如果相等则返回true.一般情况下, ...

  3. 增加线程异步发送消息的方法一(Thread)

    @RequestMapping(value="order/updateOrder.do") public String updateOrder(HttpServletRequest ...

  4. node.js 的事件驱动

    events 模块只提供了一个对象: events.EventEmitter. EventEmitter 的核心就是事件发射与事件监听器功能的封装.EventEmitter 的每个事件由一个事件名和若 ...

  5. What does "size" in int(size) of MySQL mean?

    What does "size" in int(size) of MySQL mean? https://alexander.kirk.at/2007/08/24/what-doe ...

  6. 高性能 Socket 组件 HP-Socket v3.2.1 正式发布

    HP-Socket 是一套通用的高性能 TCP/UDP Socket 组件,包含服务端组件.客户端组件和 Agent 组件,广泛适用于各种不同应用场景的 TCP/UDP 通信系统,提供 C/C++.C ...

  7. Maven学习随笔一——Maven安装报错处理(mvn -v, 提示不是内部命令的问题)

    今天心血来潮学习maven,可是光安装就花了个把小时,好坑有木有! 安装过程可百度,各种经贴,不详. 控制台输入  mvn -v ,如果报错,很可能是你的java/maven的环境变量配置出了点问题: ...

  8. 使用CSS3制作立体效果的导航菜单

    效果如下: 也可以点击网址查看效果:http://keleyi.com/keleyi/phtml/html5/12.htm 请使用支持CSS3的浏览器访问本页面,获得更好效果. 源代码: <st ...

  9. [python]沪深龙虎榜数据导入通达信的自选板块,并标注于K线图上

    将沪深龙虎榜数据导入通达信的自选板块,并标注于K线图上 原理:python读取前一次处理完的计算5日后涨跌幅输出的csv文件 文件名前加"[paint]" 安照通达信的画图文件和板 ...

  10. 原生JS:RegExp对象详解

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...