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 ...
随机推荐
- C#判断字符串是否是数字
/// <summary> /// 判断字符串是否是数字 /// </summary> public static bool IsNumber(string s) { if ( ...
- python基础之面对对象
Python3 面向对象 Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的.本章节我们将详细介绍Python的面向对象编程. 如果你以前没有接触 ...
- 《Ext JS模板与组件基本框架图----组件》
本节主要从七个方面讲解组件,组件时什么,它的作用,它的构架,以及怎么创建和周期还有常见的配置项,属性方法和事件以及其层级是什么都进行整理,希望对大家有帮助. 组件的基础知识.png 2 Abstrac ...
- P2P核心业务体系
看似一个简单的充值.提现按钮,背后可是巨多的逻辑和业务处理.
- 1 为什么搭建.Net core下的云开发框架
几年前我组织开发了综合业务管理系统,该系统包含系统门户.业务信息.联系处置.数据查询.指标报表等功能板块,其中涵盖了门户定制.工作流引擎.自定义表单.指标计算.通用数据展示.通用后台服务.用户授权认证 ...
- JS+HTML5的Canvas画图模拟太阳系运转
查看效果:http://hovertree.com/texiao/html5/9.htm 地球自传 http://hovertree.com/texiao/html5/8.htm 代码如下: < ...
- django基础篇
Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...
- React-Native性能优化点
shouldComponentUpdate 确保组件在渲染之后不需要再更新的,即静态组件,尽量在其中增加shouldComponentUpdate方法,防止二次消耗所产生的性能消耗 shouldCom ...
- Docker 从零开始制作基础镜像[centos]
http://www.oschina.net/news/62897/docker-hub-contains-high-risk-vulnerabilities 这里有个统计,docker官方和个人发布 ...
- Linux命令操作
该命令的功能是将给出的文件或目录拷贝到另一文件或目录中,就如同DOS下的copy命令一样,功能非常强大. 语法: cp [选项] 源文件或目录 目标文件或目录 说明:该命令把指定的源文件复制到目标文件 ...