当前位置:网站首页>LeetCode 109. 有序链表转换二叉搜索树
LeetCode 109. 有序链表转换二叉搜索树
2022-08-10 11:09:00 【水菜笔】
原题网址:https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/
有序链表转为高度平衡的二叉搜索树。
有序,高度平衡,所以就从链表的中间分,形成树,用到了归并思想
// 还得是高度平衡的二叉搜索树。座椅必须以链表的中点分开。
// 由于是有序的,所以遍历链表,逐个添加后依旧是链表结构,不行。
public TreeNode sortedListToBST(ListNode head) {
return mergeListToBST(head,null);
}
// 注意这里的区间是左闭右开
private TreeNode mergeListToBST(ListNode head, ListNode tail) {
// 遍历完了链表,因为是左闭右开的区间
if(head == tail) {
return null;
}
// 这个是只有一个元素了
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;
}
边栏推荐
猜你喜欢

网络基础(第一节)

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

APP automation testing practice based on UiAutomator2+PageObject mode

2022年裁员潮,失业程序员何去何从?

MLX90640 红外热成像仪测温传感器 手机 APP 软件 RedEye 连接详细

A case of violent parameter tuning in machine learning

Network sockets (UDP and TCP programming)

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

A little self-deprecating deconstruction about farmers "code"

StoneDB 文档捉虫活动第一季
随机推荐
Licking Exercise - 60 Maximum key-value sum of binary search subtrees
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
rider内Mono脚本找不到引用资源
不止跑路,拯救误操作rm -rf /*的小伙儿
Nocalhost - 让云原生时代的开发更高效
codevs 2370 小机房的树 (LCA)
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
单目操作符(含原码反码补码转换)
OPNsense安装配置Zenarmor
【机器学习】浅谈正规方程法&梯度下降
Unsafe的一些使用技巧
LeetCode50天刷题计划(Day 19—— 在排序数组中查找元素的第一个和最后一个位置(9.10-10.40)
如何使用工程仪器设备在线监测管理系统
LeetCode 138. 复制带随机指针的链表
使用JMeter进行MySQL的压力测试
力扣练习——56 寻找右区间
POJ 3101 Astronomy (Mathematics)
Some tips for using Unsafe
LeetCode_152_乘积最大子数组
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded