当前位置:网站首页>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;
}
边栏推荐
- 实现内网穿透的最佳解决方案(无实名认证,完全免费)
- 有哪些好用的性能测试工具推荐?性能测试报告收费标准
- 什么是幂等性?四种接口幂等性方案详解!
- 不止跑路,拯救误操作rm -rf /*的小伙儿
- 孩子自律性不够?猿辅导:计划表要注意“留白”给孩子更多掌控感
- Some tips for using Unsafe
- 单目操作符(含原码反码补码转换)
- WeChat applet, global variables change in one place and the state in other places also changes.
- 【小程序 | 启航篇】一文打通任督二脉
- Interviewer: How are Dao, Service, Controller, Util, and Model divided in the project?
猜你喜欢
SQL优化最强总结 (建议收藏~)
CPU多级缓存与缓存一致性
推荐6个自媒体领域,轻松易上手
Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
Network sockets (UDP and TCP programming)
How to join We Media, learn about these 5 monetization modes, and make your account quickly monetize
Emulate stm32 directly with proteus - the programmer can be completely discarded
ViT结构详解(附pytorch代码)
WeChat applet, global variables change in one place and the state in other places also changes.
随机推荐
软件架构简介
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
flask-restplus接口地址404问题
力扣练习——62 有效的数独
Licking Exercise - 60 Maximum key-value sum of binary search subtrees
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
基于UiAutomator2+PageObject模式开展APP自动化测试实战
How to join We Media, learn about these 5 monetization modes, and make your account quickly monetize
From the product dimension, why can't we fully trust Layer2?
自媒体爆款标题怎么写?手把手教你写热门标题
LeetCode50天刷题计划(Day 19—— 在排序数组中查找元素的第一个和最后一个位置(9.10-10.40)
ViT结构详解(附pytorch代码)
10 个 Reduce 常用“奇技淫巧”
不止跑路,拯救误操作rm -rf /*的小伙儿
Where can I view the version record of WeChat applet submission review history?
单目操作符(含原码反码补码转换)
Stroke Practice - 62 Valid Sudokus
Analysis of the implementation principle of UUID from the perspective of source code
网络套接字(UDP和TCP编程)
Centos7环境使用Mysql离线安装包安装Mysql5.7