描述

  • 给定一个有序列表,将其转换成为一个平衡搜索二叉树
  • 题不难,不过在讨论中发现此题的中序遍历用法略有不同,感觉有点意思
  • 手写一遍加深印象
  • 暴力解法,链表转数组,额外空间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:
  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.
  • 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的更多相关文章

  1. [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 ...

  2. 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 ...

  3. [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 ...

  4. 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 ...

  5. LeetCode 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树

    第108题 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定有序数组: [-10 ...

  6. 看动画学算法之:平衡二叉搜索树AVL Tree

    目录 简介 AVL的特性 AVL的构建 AVL的搜索 AVL的插入 AVL的删除 简介 平衡二叉搜索树是一种特殊的二叉搜索树.为什么会有平衡二叉搜索树呢? 考虑一下二叉搜索树的特殊情况,如果一个二叉搜 ...

  7. Java实现平衡二叉搜索树(AVL树)

    上一篇实现了二叉搜索树,本章对二叉搜索树进行改造使之成为平衡二叉搜索树(Balanced Binary Search Tree). 不平衡的二叉搜索树在极端情况下很容易退变成链表,与新增/删除/查找时 ...

  8. 二叉搜索树、AVL平衡二叉搜索树、红黑树、多路查找树

    1.二叉搜索树 1.1定义 是一棵二叉树,每个节点一定大于等于其左子树中每一个节点,小于等于其右子树每一个节点 1.2插入节点 从根节点开始向下找到合适的位置插入成为叶子结点即可:在向下遍历时,如果要 ...

  9. LeetCode--108--将有序数组转化为二叉搜索树

    问题描述: 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定有序数组: [-10 ...

  10. 算法:非平衡二叉搜索树(UnBalanced Binary Search Tree)

    背景 很多场景下都需要将元素存储到已排序的集合中.用数组来存储,搜索效率非常高: O(log n),但是插入效率比较低:O(n).用链表来存储,插入效率和搜索效率都比较低:O(n).如何能提供插入和搜 ...

随机推荐

  1. Python获取jsonp数据

    使用python爬取数据时,有时候会遇到jsonp的数据格式,由于不是json的,所以不能直接使用json.loads()方法来解析,需要先将其转换为json格式,再进行解析.在前面讲了jsonp的原 ...

  2. Hardhat 开发框架 - Solidity开发教程连载

    Decert.me 要连载教程了, <Solidity 开发教程> 力求系统.深入的介绍 Solidity 开发, 同时这是一套交互式教程,你可以实时的修改教程里的合约代码并运行. 本教程 ...

  3. autojs系列-js入门1

    开头 确保 Autojs 和 adb 还有模拟器安装调试完成之后,就可以进行js的学习了 调试安装一部分步骤可以参考 https://www.cnblogs.com/c-keke/p/14919615 ...

  4. 2023-04-12:使用 Go 重写 FFmpeg 的 extract_mvs.c 工具程序,提取视频中的运动矢量信息。

    2023-04-12:使用 Go 重写 FFmpeg 的 extract_mvs.c 工具程序,提取视频中的运动矢量信息. 答案2023-04-12: 主要的过程包括: 打开输入视频文件并查找视频流信 ...

  5. 2021-05-22:假设所有字符都是小写字母, 大字符串是str,arr是去重的单词表, 每个单词都不是空字符串且可以使用任意次。使用arr中的单词有多少种拼接str的方式。 返回方法数。

    2021-05-22:假设所有字符都是小写字母, 大字符串是str,arr是去重的单词表, 每个单词都不是空字符串且可以使用任意次.使用arr中的单词有多少种拼接str的方式. 返回方法数. 福大大 ...

  6. 2021-07-28:最短的桥。在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。返回必须翻转的

    2021-07-28:最短的桥.在给定的二维二进制数组 A 中,存在两座岛.(岛是由四面相连的 1 形成的一个最大组.)现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛.返回必须翻转的 ...

  7. 2021-10-13:单词接龙。字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:序列中第一个单词是 beginWord 。序列中最后

    2021-10-13:单词接龙.字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:序列中第一个单词是 beginWord .序列中最后 ...

  8. Selenium - 基础知识介绍

    Selenium - 基础知识介绍 介绍 Selenium是ThoughtWorks员工在业余时间开发并维护的开源项目,并且在ThoughtWorks的项 目中被广泛应用. 简单地说,Selenium ...

  9. GitLib详细使用手册(windows系统)

    Git是一个开源的分布式版本控制系统,可以有效.高速地处理从很小到非常大的项目版本管理. 对gitlab的常见的使用有建立仓库.提交代码.更新代码.回滚代码.显示/修改日志.拉取分支.解决冲突.设置比 ...

  10. [abc279 G] At Most 2 Colors

    G - At Most 2 Colors (atcoder.jp) 重点讲解方法三,因为方法三是蒟蒻都能想出来的方法一和方法二都可以借助方法三的思想推出 方法一 这是最简单的设置状态的方法,\(dp[ ...