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 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的更多相关文章
- 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 ...
- Leetcode: Convert sorted list to binary search tree (No. 109)
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...
- [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 ...
- [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. 这道 ...
- 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 ...
- 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 ...
- 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 ...
- [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 ...
- 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 ...
随机推荐
- Oracle函数-DECODE
DECODE翻译为解码或译码,因为它可以把查询结果翻译成令用户容易理解的内容. 语法: expr: 表达式 search:搜索值 result:结果值 default:默认值 DECODE函数的第一个 ...
- POJ-3061
算法: 1. 定义两个整数N和S,输入序列长度到N,输入最小子序列和下界到S. 2. 定义一个数组arr[100002],从arr[1]开始依次输入N个序列元素到arr. 3. 定义一个整数ans,初 ...
- phpstorm10.0.3破解版安装教程及汉化方法
phpstorm是一个轻量级且便捷的PHP IDE,其旨在提供用户效率,可深刻理解用户的编码,提供智能代码补全,快速导航以及即时错误检查.不但是php开发的利器,前端开发也是毫不逊色的.下面记录php ...
- nhibernate 中 lazy="no-proxy" 时的问题
在 nhibernate,如果将实体的一个关联属性配置为 lazy="no-proxy",那么,从其他属性计算出来的属性不能正确更新.例如,将以下代码中 Foo.Bar 配置为 l ...
- UML简单例子
平时最常用到的UML图包括:用例图.类图.序列图.状态图. 用例图 主要是描述系统具有的一个功能单元.通常包含角色和用例.角色通常表示为一个系统用户,用例通常表示为系统具有的一个功能.通过用例图我们可 ...
- 小记max-with与 max-device-width
max-with是浏览器的宽度,max-device-width是设备显示器的宽度 浏览器宽度不等于显示器宽度 浏览器可以缩小 1.max-device-width是设备整个显示区域的宽度,例如,真实 ...
- JS高程3.基本概念(2)
1.ECMAScript数据类型 5种简单数据类型,分别是: Undefined Null Boolean Number String 1种复杂数据类型: Object (1)typeof操作符--检 ...
- 【小贴士】探一探javascript中的replace
javascript字符串与数组有很多精巧的方法,比如splice.indexOf,而replace在字符串处理中偶尔会产生让人愉悦的效果 比如underscore中的模板引擎替换部分,又如信用卡分割 ...
- GPS各种地图坐标系转换(转载)
http://my.oschina.net/fankun2013/blog/338100 地图供应商比较多,产生了许多地图坐标.地图坐标正确转换是个问题.在之前开发地图应用的时候发现从WGS84坐标系 ...
- cordova for ios: Unable to simultaneously satisfy constraints.
使用cordova开发ios项目的时候,在上传图片碰到一个问题.使用html的<input type="file"/>标签来选择照片或者拍照片,引起了布局报错,然后图片 ...