由有序链表构建平衡二叉搜索树-sortedListToBST
描述
- 给定一个有序列表,将其转换成为一个平衡搜索二叉树
- 题不难,不过在讨论中发现此题的中序遍历用法略有不同,感觉有点意思
- 手写一遍加深印象
- 暴力解法,链表转数组,额外空间O(N),递归遍历搞定。几分钟解决,但显然不是最优。
- 其次思考类似于红黑树进行节点旋转,后来发现成本较高。
- 到讨论区发现solution-2的解法:计数得到节点总数,知道节点数就可以确定一种满足要求的BST结构,然后使用中序遍历,将列表元素填入BST对应节点。
Description
109. Convert Sorted List to Binary Search Tree
Medium
2382
90
Add to List
Share
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [0]
Output: [0]
Example 4:
Input: head = [1,3]
Output: [3,1]
Constraints:
The number of nodes in head is in the range [0, 2 * 104].
-10^5 <= Node.val <= 10^5
Solution-1
- traversal the list and add all elements into a array
- then convert this problem to 108_convert_sorted_array_to_binary_search_tree.
- time cost : O(N) + O(N) + O(N) ~ O(N) : traversal the list + recursive construct tree + read the elements in list
- space cost : O(N) + O(logN) ~ O(N) : array space and recursive stack cost.
AC Result
- Runtime: 132 ms, faster than 47.94% of Python online submissions for Convert Sorted List to Binary Search Tree.
- Memory Usage: 25.5 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
show me the code
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
Runtime: 52 ms, faster than 99.19% of Python online submissions for Convert Sorted Array to Binary Search Tree.
Memory Usage: 17 MB, less than 35.16% of Python online submissions for Convert Sorted Array to Binary Search Tree.
"""
nums_len = len(nums)
if(nums_len == 0):
return None
if(nums_len == 1):
return TreeNode(nums[0])
mid = nums_len / 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[0:mid])
root.right = self.sortedArrayToBST(nums[mid + 1 :])
return root
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
Runtime: 132 ms, faster than 47.94% of Python online submissions for Convert Sorted List to Binary Search Tree.
Memory Usage: 25.5 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
"""
head_arr = []
cur_point = head
while(cur_point):
head_arr.append(cur_point.val)
cur_point = cur_point.next
return self.sortedArrayToBST(head_arr)
Solution-2
- inorder Traversal to fill all elements in list in a new tree construct by recursive.
how to understand this solution:
- we count all elements in list so that we can know the tree constructure which corresponds the conditions of BST
- inorder traversal the specified BST
- fill the elements in list into the target tree.
this is mean we traversal the tree by inorder function, fill the sorted elements at specified positions.
time cost : O(N) + O(N) + O(N) ~ O(N) : traversal the list + recursive construct tree + read the elements in list
space cost : O(1) + O(logN) ~ O(logN) : recursive stack cost.
AC Result
- Runtime: 124 ms, faster than 80.95% of Python online submissions for Convert Sorted List to Binary Search Tree.
- Memory Usage: 25.7 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
show me the code
def sortedListToBST(self, head):
if(None == head):
return None
cur_point = head
head_count = 0
while(cur_point):
head_count += 1
cur_point = cur_point.next
self.cur_point = head
return self.inner_sorted_list_to_bst(1, head_count)
def inner_sorted_list_to_bst(self, start_idx, end_idx):
'''
inorder Traversal to fill all elements in list in a new tree construct by recursive.
how to understand this solution:
1. we count all elements in list so that we can know the tree constructure which corresponds the conditions of BST
2. inorder traversal the specified BST
3. fill the elements in list into the target tree.
this is mean we traversal the tree by inorder function, fill the sorted elements at specified positions.
Runtime: 124 ms, faster than 80.95% of Python online submissions for Convert Sorted List to Binary Search Tree.
Memory Usage: 25.7 MB, less than 21.90% of Python online submissions for Convert Sorted List to Binary Search Tree.
:param start_idx:
:param end_idx:
:return:
'''
if(start_idx > end_idx):
return None
mid_idx = start_idx + (end_idx - start_idx)/2
left = self.inner_sorted_list_to_bst(start_idx, mid_idx -1)
root = TreeNode(self.cur_point.val)
root.left = left
self.cur_point = self.cur_point.next
root.right = self.inner_sorted_list_to_bst(mid_idx +1 , end_idx)
return root
由有序链表构建平衡二叉搜索树-sortedListToBST的更多相关文章
- [LeetCode] 109. 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 ...
- Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树 &&convert-sorted-array-to-binary-search-tree——将数列转换为bst
Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in as ...
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Fo ...
- 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 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树
第108题 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定有序数组: [-10 ...
- 看动画学算法之:平衡二叉搜索树AVL Tree
目录 简介 AVL的特性 AVL的构建 AVL的搜索 AVL的插入 AVL的删除 简介 平衡二叉搜索树是一种特殊的二叉搜索树.为什么会有平衡二叉搜索树呢? 考虑一下二叉搜索树的特殊情况,如果一个二叉搜 ...
- Java实现平衡二叉搜索树(AVL树)
上一篇实现了二叉搜索树,本章对二叉搜索树进行改造使之成为平衡二叉搜索树(Balanced Binary Search Tree). 不平衡的二叉搜索树在极端情况下很容易退变成链表,与新增/删除/查找时 ...
- 二叉搜索树、AVL平衡二叉搜索树、红黑树、多路查找树
1.二叉搜索树 1.1定义 是一棵二叉树,每个节点一定大于等于其左子树中每一个节点,小于等于其右子树每一个节点 1.2插入节点 从根节点开始向下找到合适的位置插入成为叶子结点即可:在向下遍历时,如果要 ...
- LeetCode--108--将有序数组转化为二叉搜索树
问题描述: 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定有序数组: [-10 ...
- 算法:非平衡二叉搜索树(UnBalanced Binary Search Tree)
背景 很多场景下都需要将元素存储到已排序的集合中.用数组来存储,搜索效率非常高: O(log n),但是插入效率比较低:O(n).用链表来存储,插入效率和搜索效率都比较低:O(n).如何能提供插入和搜 ...
随机推荐
- LeetCode 周赛 343(2023/04/30)结合「下一个排列」的贪心构造问题
本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 提问. 大家好,我是小彭. 今天是五一假期的第二天,打周赛的人数比前一天的双周赛多了,难道大家都只玩一天吗?这场周赛 ...
- 2022-09-26:以下go语言代码输出什么?A:{“Time“: “2020-12-20T00:00:00Z“, “N“: 5 };B:“2020-12-20T00:00:00Z“;C:{“N“:
2022-09-26:以下go语言代码输出什么?A:{"Time": "2020-12-20T00:00:00Z", "N": 5 }:B: ...
- 2021-01-18:java中,HashMap的创建流程是什么?
福哥答案2021-01-18: jdk1.7创建流程:三种构造器.1.初始容量不能为负数,默认16.2.初始容量大于最大容量时,初始容量等于最大容量.3.负载因子必须大于0,默认0.75.4.根据初始 ...
- 2022-02-25:k8s安装zookeeper,yaml如何写?找份北京的golang后端工作,35岁,有人收我吗?
2022-02-25:k8s安装zookeeper,yaml如何写?找份北京的golang后端工作,35岁,有人收我吗? 答案2022-02-25: yaml如下: apiVersion: apps/ ...
- Github疯传!200本计算机经典书籍!
好书在精不在多,每一本经典书籍都值得反复翻阅,温故而知新! 下面分享几本计算机经典书籍,都是我自己看过的. 重构 改善既有代码的设计 就像豆瓣评论所说的,看后有种醍醐灌顶.欲罢不能的感觉.无论你是初学 ...
- 2023-05-29:给你一个由 n 个正整数组成的数组 nums 你可以对数组的任意元素执行任意次数的两类操作 如果元素是 偶数 ,除以 2 例如,如果数组是 [1,2,3,4] 那么你可以对最后一
七.设计算法,仅使用三次实数乘法即可完成复数 a+bi和c+di 相乘.算法需接收a.b.c和d 为输入,分别生成实部 ac-bd 和虚部ad+bc. 文心一言: 可以使用如下算法来计算复数 a+bi ...
- 火爆,Github标星240K的编程学习路线图,适合所有程序员!
推荐一个涵盖开发.运维.产品设计的学习路线图,在Github已经start超过240K,包括各门编程语言! 一.涵盖的路线图 该项目涵盖了非常全面的学习路线图: 前端路线图 后端路线图 ASP.NET ...
- 基于 Dash Bio 的生物信息学数据可视化
Dash 是用于搭建响应式 Web 应用的 Python 开源库.Dash Bio 是面向生物信息学,且与 Dash 兼容的组件,它可以将生物信息学领域中常见的数据整合到 Dash 应用程序,以实现响 ...
- [ARM 汇编]进阶篇—异常处理与中断—2.4.2 ARM处理器的异常向量表
异常向量表简介 在ARM架构中,异常向量表是一组固定位置的内存地址,它们包含了处理器在遇到异常时需要跳转到的处理程序的入口地址.每个异常类型都有一个对应的向量地址.当异常发生时,处理器会自动跳转到对应 ...
- 现代C++学习指南-具体类
类作为C++中重要的概念之一,有着众多的特性,也是最迷人的部分! 类是一个加工厂,开发者使用C++提供的各种材料组装这个工厂,使得它可以生产出符合自己要求的数据,通过对工厂的改造,可以精细控制对象从出 ...