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 ...
随机推荐
- 转载:《TypeScript 中文入门教程》 5、命名空间和模块
版权 文章转载自:https://github.com/zhongsp 建议您直接跳转到上面的网址查看最新版本. 关于术语的一点说明: 请务必注意一点,TypeScript 1.5里术语名已经发生了变 ...
- UVALive 6911---Double Swords(贪心+树状数组(或集合))
题目链接 https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...
- MyBatis的mapper
在前面的学习中,我们还在写一些接口啊,实现类啊,是不是感觉好low的... 其实,我们是可以不用写接口的实现类的,今天就带着大家一起学习一下,当然,我是回顾的. 看下面的结构,是不是没实现类呢! 源码 ...
- Kerberos简介
Kerberos协议: Kerberos协议主要用于计算机网络的身份鉴别(Authentication), 其特点是用户只需输入一次身份验证信息就可以凭借此验证获得的票据(ticket-grantin ...
- 无限级ddsmoothmenu菜单实例
点击这里查看效果以横向ddsmoothmenu下来菜单为例,以下是实现代码: <base target="_blank" /><link rel="st ...
- ArcGIS API for Silverlight 使用GeometryService求解线与线的交点
///画线 void btn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Button btn = sender as B ...
- app:clean classes Exception
Error:Execution failed for task ':app:clean'.> Unable to delete directory: C:\Users\LiuZhen\Deskt ...
- IOS开发基础知识--碎片3
十二:判断设备 //设备名称 return [UIDevice currentDevice].name; //设备型号,只可得到是何设备,无法得到是第几代设备 return [UIDevice cur ...
- IOS 日期的简洁格式展示
首先我要解释一下标题的意义,日期的简洁格式展示,之所以简介,是因为让人一目了然,不需要思考是什么时候. 在详细一点就是我们在微信朋友圈中 所看到的时间格式. 例如:刚刚 -几分钟前-几小时前等等. 今 ...
- C# 6.0新特性
因为在博客中给出的代码大多数都使用了C#6.0的新特性,如果各位对C#6.0还不了解,可以简单的看一下这篇随笔.o( ̄▽ ̄)d 先来看一个Point类 public class Point { pub ...