当前位置:网站首页>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;
}
边栏推荐
- leetcode 823. Binary Trees With Factors(因子二叉树)
- 不止跑路,拯救误操作rm -rf /*的小伙儿
- 力扣练习—— 矩形区域不超过 K 的最大数值和(hard)
- Since the media hot style title how to write?Taught you how to write the title
- 从脚本到剪辑,影像大师亲授的后期制作秘籍
- 力扣练习——61 根据字符出现频率排序
- HDU 1520 Anniversary party (tree dp)
- Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
- Flutter气泡框实现
- Spss-多元回归案例实操
猜你喜欢
随机推荐
快速上手,征服三种不同分布式架构调用方案
Intel pushes 20220809 CPU microcode update to patch Intel-SA-00657 security vulnerability
如何使用工程仪器设备在线监测管理系统
Article take you understand interrupt the key driver of polling mechanism
不止跑路,拯救误操作rm -rf /*的小伙儿
Buckle Exercise - 61 Sort by frequency of characters
基于UiAutomator2+PageObject模式开展APP自动化测试实战
杭电多校-Loop-(不确定性贪心+线段树)
英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞
力扣练习——63 找到字符串中所有字母异位词
2022年裁员潮,失业程序员何去何从?
Licking Exercise - 60 Maximum key-value sum of binary search subtrees
Flutter气泡框实现
Centos7 environment uses Mysql offline installation package to install Mysql5.7
基于UiAutomator2+PageObject模式开展APP自动化测试实战
ENVI 5.3软件安装包和安装教程
OSSCore 开源解决方案介绍
态路小课堂丨如何为CXP光模块选择光纤跳线?
模块九 - 设计电商秒杀系统
基于UiAutomator2+PageObject模式开展APP自动化测试实战