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 ...
随机推荐
- VMWare 安装 Mac OS X10.10 Yosemite
OS X Yosemite 新功能特性 Mac OS X10.10 GM3|OS X 10.10 Yosemite 正式版下载 如何在虚拟机中安装苹果mac系统图示说明 vm10虚拟机安装Mac OS ...
- 编程模式之模板方法模式(Template Method)
模板方法模式由两个角色组成:父类角色,子类角色. 父类角色:提供模板. 子类角色:为父类模板提供实现. 类图: JAVA代码: AbstractClass.java package com.templ ...
- 编译android 4.4.2
1.获取Android源码 (1)下载repo 在用户目录下创建一个bin文件夹来存放repo,并把该路径设置到环境变量中 mkdir ~/bin PATH=~/bin:$PATH 下载repo脚本 ...
- 十二种获取Spring的上下文环境ApplicationContext的方法
转载:https://my.oschina.net/u/2391658/blog/729414
- 《javascript面向对象精要》读书笔记
<javascript面向对象精要> 买这本书的原因主要是因为作者,Nicholas C. Zakas 牛X闪闪的js专家,读过js高程的应该都知道他,而这本书是他的最新力作,感觉也是js ...
- 给DB数据表加强制索引
DB2 数据库会根据DB层的统计值决定 根据查询条件走哪一个索引,某些情况下,由于未知原因,索引会走偏,故程序中可以规定程序走哪一个索引来避免索引走偏的情况发生. 强制走索引的 实例代码如下: SEL ...
- SharePoint 2013 配置Excel Services
前言:本文主要介绍如何启用SharePoint 2013版本Excel Services服务,并配置Excel Web Access部件,使Excel文档可以显示在Web页面中. 简单说一下流程,Sh ...
- Sharepoint学习笔记—ECM系列—文档列表的Metedata Navigation与Key Filter功能的实现
如果一个文档列表中存放了成百上千的文档,想要快速的找到你想要的还真不是件容易的事,Sharepoint提供了Metedata Navigation与Key Filter功能可以帮助我们快速的过滤和定位 ...
- 【代码笔记】iOS-UITextField设置placeholder颜色
一,效果图. 二,工程图. 三,代码. RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController ...
- ButterKnife 8.2.1 大圣归来
零.前言 ButterKnife是一个视图注入的框架,主要帮我们解决无脑的findViewById.设置监听事件等等体力劳动. 一.引入 好消息是ButterKnife终于使用apt生成代码了,首先在 ...