算法:把排好序的链表转换为二叉排序树Convert Sorted List to Binary Search Tree
题目
109. Convert Sorted List to Binary Search Tree
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 * 10^4]
. -10^5 <= Node.val <= 10^5
解法一:转为数组后,根据数组序号二分组装成二叉排序树
思路:
因为树有左右分叉,用递归解法。
- 把链表的值,组装成数组;
- 根据数组的索引,递归调用组装成二叉排序树
# Definition for singly-linked list.
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next
# Definition for a binary tree node.
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = right
class ConvertSortedListToBinarySearchTree:# Convert the given linked list to an arrydef mapListToValues(self, head: ListNode):vals = []while head:vals.append(head.val)head = head.nextreturn valsdef sortedListToBST(self, head: ListNode) -> TreeNode:# check edgeif head == None :return Noneif head.next == None:return TreeNode(head.val)# Form an array out of the given linked list and then# use the array to form the BSTvalues = self.mapListToValues(head)# l and r represent the start and end of the given arraydef convertListToBST(l, r):# Invalid caseif l > r:return None# Middle element forms the root.mid = (l + r) // 2node = TreeNode(values[mid])# Baes case for when there is only one element left in the arrayif l == r:return node# Recursively fom BST on the two halvesnode.left = convertListToBST(l, mid - 1)node.right = convertListToBST(mid + 1, r)return nodereturn convertListToBST(0, len(values) - 1)
解法二:找链表中的中间节点,组装成二叉排序树
组装树的方法是用递归,如果能持续找到中间节点,就可以持续组装树的middle, middle.left, middle.right.
找中间节点的方法,用快慢两个指针,慢指针每次走一步,快指针每次走两步;这样子就可以找出中间节点。
# Definition for singly-linked list.
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next
# Definition for a binary tree node.
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = right
class ConvertSortedListToBinarySearchTree:def findMiddle(self, head: ListNode):# The pointer used to disconnect the left half from the mid node.preNode = NoneslowNode = headfastNode = head# Iterate until fastNode doesn't reach the end of the linked list.while fastNode and fastNode.next:preNode = slowNodeslowNode = slowNode.nextfastNode = fastNode.next.next# Handling the case when slowNode was equal to headif preNode:preNode.next = Nonereturn slowNodedef sortedListToBST2(self, head: ListNode):# If the head doesn't exist, then the linked list is emptyif not head:return None# Find the middle element for the listmid = self.findMiddle(head)# the mid becones the root of the BST.node = TreeNode(mid.val)# Base case when there is just one element in the linked listif head == mid:return node# Recursively form balanced BSTs using the left and right halves of the original list.node.left = self.sortedListToBST2(head)node.right = self.sortedListToBST2(mid.next)return node
参考
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/solution/
算法:把排好序的链表转换为二叉排序树Convert Sorted List to Binary Search Tree相关推荐
- 【链表递归构造二叉树】LeetCode 109. Convert Sorted List to Binary Search Tree
LeetCode 109. Convert Sorted List to Binary Search Tree Solution1:我的答案 偷鸡摸狗的做法 /*** Definition for s ...
- LeetCode Convert Sorted List to Binary Search Tree(有序单链表转为平衡二叉树)
题意:给出一个有序的单链表,将其转换成平衡二叉树 思路:因为是有序的,所以可以将其分成两部分,前部分作为左子树,后部分作为右子树 代码如下: class ListNode {int val;ListN ...
- leetcode 108. Convert Sorted Array to Binary Search Tree | 108. 将有序数组转换为二叉搜索树(Java)
题目 https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 题解 经典二分,不解释了,直接看代码 /*** ...
- 【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】...
[109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 ...
- 笔试算法题(58):二分查找树性能分析(Binary Search Tree Performance Analysis)
议题:二分查找树性能分析(Binary Search Tree Performance Analysis) 分析: 二叉搜索树(Binary Search Tree,BST)是一颗典型的二叉树,同时任 ...
- 数据结构与算法(八)二分搜索树(Binary Search Tree)
本文主要包括以下内容: 二分搜索树的基本概念 二分搜索树的基本操作 1. 插入 2. 删除 3. 查询 实现二分搜索树 二分搜索树的不足 二分搜索树的基本概念 二分搜索树(英语:Binary Sear ...
- PAT甲级1043 Is It a Binary Search Tree :[C++题解]判断二叉搜索树BST、给定前序序列和中序序列
文章目录 题目分析 题目链接 题目分析 二叉搜索树(BST):左子树小于根结点,右子树大于等于根结点. 二叉搜索树的中序遍历一定是有序序列.所谓中序遍历:先访问左子树,再访问根结点,最后访问右子树. ...
- 数据结构与算法(C++)– 二叉查找树(Binary Search Tree )
数据结构与算法(C++)– 二叉查找树(Binary Search Tree ) 1.二叉查找树(BST) 定义: 假设二叉树的节点都是不同的数,对于树点的任一节点,它的左子树都小于它,它的右子树都大 ...
- 数据结构与算法 / 二叉搜索树(Binary Search Tree)
目录 一.定义 二.性质 三.时间复杂度分析 四.遍历方式 五.源码 一.定义 若左子树不空,则左子树上的所有的节点都小于它的根节点. 若右子树不空,则右子树上的所有的节点都大于它的根节点. 左右子树 ...
- 高级数据结构与算法 | 二叉搜索树(Binary Search Tree)
文章目录 二叉搜索树的概念 二叉搜索树的作用 排序 查找 实现思路 查找 插入 删除 删除.拷贝等 代码实现 K模型 KV模型 二叉搜索树的概念 二叉搜索树又叫做二叉排序树,他是一个具有以下特性的二叉 ...
最新文章
- HDFS 文件格式——SequenceFile RCFile
- vs2008环境下MFC对注册表的读写操作
- 4.android.mk编写规范
- javaweb中实现分页,持续更新……
- vue中pdf预览组件_Vue+ElementUI使用vue-pdf实现预览功能
- Python精选库大全,建议收藏留用!
- nginx mozilla_Android进入汽车市场,Mozilla进入电视市场,等等
- 联网智能设备安全态势季度报告(2021年第2季度)
- Datetime 24小时制
- 词汇的积累与遣词造句 —— 准确的表达、新鲜的词汇
- 实现加载页Loading Page 的几种方法
- matlab 均值滤波
- C语言约瑟夫环(简单版)
- UML-----实现图(构件图、部署图)
- 腾讯视频TS文件转MP4
- 不能创建对象qmdispatch_按键精灵更新时提示 ActiveX 部件不能创建对象 错误代码 800a01ad_电脑故障...
- 坐标正反算例题_坐标正算公式例题
- 字节跳动实习面试:三面无修改公开,看看他到底通过了吗?
- Chrome插件离线安装方法及编程思路
- 经典的大学学习生活心得
热门文章
- python xpath爬虫_[爬虫]python下的xpath清洗数据之html数据清洗
- python中iter方法_Python中的迭代器(iter())函数。
- case when的判断顺序_Sql 中的if 判断 case... when
- ××× L2TP over IPSec 配置
- Android查看appPackage和Activity的多种方法
- flowable实现多实例节点的自由跳转
- 《BGP设计与实现》一2.11 总结
- javascript 计时器,消失计时器
- Oracle高级查询之GROUP BY
- Node.js开发指南中的例子(mysql版)