当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
皕杰报表在传参乱码
如何使用工程仪器设备在线监测管理系统
振弦传感器及核心VM系列振弦采集模块
Network sockets (UDP and TCP programming)
APP automation testing practice based on UiAutomator2+PageObject mode
Does your child lack self-discipline?Ape Counseling: Pay attention to "blank" in the schedule to give children more control
建校仅11年就入选“双一流” ,这所高校是凭什么做到的?
[E-commerce operation] Do you really understand social media marketing (SMM)?
L2 applications from a product perspective: why is it a playground?
Nocalhost - 让云原生时代的开发更高效
随机推荐
Ssm framework construction process [easy to understand]
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
Where can I view the version record of WeChat applet submission review history?
开源的作者,也有个生活问题
中芯CIM国产化项目暂停?上扬软件:未停摆,改为远程开发!
不止跑路,拯救误操作rm -rf /*的小伙儿
实现内网穿透的最佳解决方案(无实名认证,完全免费)
接口定义与实现
网络套接字(UDP和TCP编程)
微信小程序,全局变量一个地方改变了其他地方的状态也跟着改变。
A case of violent parameter tuning in machine learning
LeetCode 86. 分隔链表
Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
LeetCode 24. 两两交换链表中的节点
jlink 与 swd 接口定义
网络基础(第一节)
Intel pushes 20220809 CPU microcode update to patch Intel-SA-00657 security vulnerability
LeetCode 92. 反转链表 II
什么是幂等性?四种接口幂等性方案详解!
LeetCode50天刷题计划(Day 18—— 搜索旋转排序数组(8.50-12.00)