当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

ViT结构详解(附pytorch代码)

学长告诉我,大厂MySQL都是通过SSH连接的

单目操作符(含原码反码补码转换)

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

Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using

APP automation testing practice based on UiAutomator2+PageObject mode

快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?

Does your child lack self-discipline?Ape Counseling: Pay attention to "blank" in the schedule to give children more control

CPU多级缓存与缓存一致性

建校仅11年就入选“双一流” ,这所高校是凭什么做到的?
随机推荐
Licking Exercise - 63 Find all anagrams in a string
Buckle Exercise - 61 Sort by frequency of characters
不止跑路,拯救误操作rm -rf /*的小伙儿
如何使用工程仪器设备在线监测管理系统
态路小课堂丨如何为CXP光模块选择光纤跳线?
LeetCode 92. 反转链表 II
【mysql】explain介绍[通俗易懂]
不止跑路,拯救误操作rm -rf /*的小伙儿
Go 事,Gopher 要学的数字类型,变量,常量,运算符 ,第2篇
StoneDB 文档捉虫活动第一季
皕杰报表在传参乱码
什么是幂等性?四种接口幂等性方案详解!
Analysis of the implementation principle of UUID from the perspective of source code
HDU 4135:Co-prime (容斥原理)
负载均衡原理分析与源码解读
[Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
gpu-admission 源码分析
零基础想自学软件测试,有没有大佬可以分享下接下来的学习书籍和路线?
jlink 与 swd 接口定义
Module 9 - Designing an e-commerce seckill system