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

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

【电商运营】你真的了解社交媒体营销(SMM)吗?

SQL优化最强总结 (建议收藏~)

AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)

英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞

Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户

态路小课堂丨如何为CXP光模块选择光纤跳线?
![[E-commerce operation] Do you really understand social media marketing (SMM)?](/img/5b/6682c613305deb3dc15401077d38a0.png)
[E-commerce operation] Do you really understand social media marketing (SMM)?

皕杰报表在传参乱码

实现内网穿透的最佳解决方案(无实名认证,完全免费)
随机推荐
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists
[Go WebSocket] 多房间的聊天室(一)思考篇
LeetCode 362. Design Hit Counter(计数器)
Introduction to Software Architecture
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
Where can I view the version record of WeChat applet submission review history?
SQL优化最强总结 (建议收藏~)
A little self-deprecating deconstruction about farmers "code"
codevs 2370 小机房的树 (LCA)
Flutter气泡框实现
单目操作符(含原码反码补码转换)
Programmers pursue technology to consolidate basic learning route suggestions
ENVI 5.3软件安装包和安装教程
力扣练习——64 最长和谐子序列
POJ 3101 Astronomy (Mathematics)
【Untitled】
Licking Exercise - 59 From Binary Search Trees to Greater Sum Trees
blocking non-blocking poll mechanism asynchronous
Chapter 22 Source Code File REST API Reference (4)
POJ 1026 Cipher (Permutation Groups)