当前位置:网站首页>LeetCode 109. Sorted Linked List Conversion Binary Search Tree
LeetCode 109. Sorted Linked List Conversion Binary Search Tree
2022-08-10 11:57:00 【Water dish pen】
原题网址:https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/
The ordered linked list is transformed into a highly balanced binary search tree.
有序,高度平衡,So it is divided from the middle of the linked list,形成树,The idea of merging is used
// It has to be a highly balanced binary search tree.The seats must be separated by the midpoint of the linked list.
// 由于是有序的,So traverse the linked list,After adding one by one, it is still a linked list structure,不行.
public TreeNode sortedListToBST(ListNode head) {
return mergeListToBST(head,null);
}
// Note that the interval here is left closed and right open
private TreeNode mergeListToBST(ListNode head, ListNode tail) {
// 遍历完了链表,因为是左闭右开的区间
if(head == tail) {
return null;
}
// This is only one element
if(head.next == tail) {
return new TreeNode(head.val);
}
ListNode midNode = getMidNode(head,tail);
TreeNode root = new TreeNode(midNode.val);
root.left = mergeListToBST(head,midNode);
root.right = mergeListToBST(midNode.next,tail);
return root;
}
private ListNode getMidNode(ListNode head, ListNode tail) {
ListNode fast = head;
ListNode slow = head;
while(fast != tail && fast.next != tail) {
fast= fast.next.next;
slow= slow.next;
}
return slow;
}
边栏推荐
- Redis常用命令
- Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
- 即时零售业态下如何实现自动做账?
- Intel pushes 20220809 CPU microcode update to patch Intel-SA-00657 security vulnerability
- 英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞
- AutoCAD Map 3D功能之一暴力处理悬挂点(延伸)
- 个推数据资产管理经验 | 教你打造数据质量心电图,智能检测数据“心跳”异常
- OPNsense安装配置Zenarmor
- OSSCore 开源解决方案介绍
- 振弦传感器及核心VM系列振弦采集模块
猜你喜欢

L2 applications from a product perspective: why is it a playground?

网络基础(第一节)

A case of violent parameter tuning in machine learning
![[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists](/img/06/9d49fc99ab684f03740deb2abc38e2.png)
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists

3款不同类型的自媒体免费工具,有效提高创作、运营效率

std::move()

基于UiAutomator2+PageObject模式开展APP自动化测试实战

推荐6个自媒体领域,轻松易上手

Intel pushes 20220809 CPU microcode update to patch Intel-SA-00657 security vulnerability

如何使用工程仪器设备在线监测管理系统
随机推荐
StoneDB Document Bug Hunting Season 1
项目部署、
Stroke Practice - 62 Valid Sudokus
振弦传感器及核心VM系列振弦采集模块
快速上手,征服三种不同分布式架构调用方案
LeetCode 445. 两数相加 II
What are some useful performance testing tools recommended? Performance testing report charging standards
Not just running away, but saving the guy who mishandled rm -rf /*
苹果逆势扩大iPhone 14系列备货,总量或达9500万部
ENVI 5.3软件安装包和安装教程
三星计划2023年开始在越南生产半导体零部件
SQL优化最强总结 (建议收藏~)
LCD驱动端与设备端名称匹配过程分析(Tiny4412)
态路小课堂丨如何为CXP光模块选择光纤跳线?
面试官:你们是如何保证接口的幂等性?
被面试官问到消息队列的丢失、重复与积压问题该如何回答
再有人问你分布式事务,把这篇扔给他
Pulling drills - 56 Finding the right interval
力扣练习——60 二叉搜索子树的最大键值和
力扣练习——58 验证二叉搜索树