当前位置:网站首页>leetcode 108:将有序数组转换为二叉搜索树
leetcode 108:将有序数组转换为二叉搜索树
2022-04-22 17:58:00 【Yingmu__】
leetcode 108:将有序数组转换为二叉搜索树
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
示例 1:

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:
示例 2:

输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。
提示:
1 <= nums.length <= 104-104 <= nums[i] <= 104nums按 严格递增 顺序排列
Related Topics
树
二叉搜索树
数组
分治
二叉树
递归
- 分析:转换为二叉搜索树,需要左右子树高度查不超过1。所以可以一颗子树区间中的中间值作为根。
- 那么左右子树的元素个数相差绝对值不超过1.
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sortedArrayToBST(nums,0,nums.length-1);
}
public TreeNode sortedArrayToBST(int[] nums,int start, int end){
if(start > end){
return null;
}
if(start == end){
return new TreeNode(nums[start]);
}
int mid = (start+end)>>1;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums,start,mid-1);
root.right = sortedArrayToBST(nums,mid+1,end);
return root;
}
}
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:41.6 MB,击败了8.57% 的Java用户
版权声明
本文为[Yingmu__]所创,转载请带上原文链接,感谢
https://blog.csdn.net/yingmu__/article/details/124338753
边栏推荐
- 因索引合并导致的MySQL死锁分析与解决实战!
- Unable to translate SQLException with Error code ‘0‘, will now try the fallback translator
- 软考高项笔记 | 信息化的五个层次
- Soft test high item notes | project schedule management
- 你知道你的手机上有多少传感器吗?
- 【C语言】getchar()函数缓冲区
- 2022年,5G芯片会有哪些值得期待的发展趋势?
- 为什么智能手机传感器市场一直是索尼占主导
- Go operation MySQL
- L1-002 printing Hourglass (20 points)
猜你喜欢

Inventory 6 open source projects of Niuniu

Notes on soft test high items | six elements of national information system

Qiu Chengtong has joined Tsinghua full time

优麒麟 22.04 LTS 版本正式发布 | UKUI 3.1开启全新体验!

Use of ES6 generator function

软考高项笔记 | 软技能

软考高项笔记 | 企业应用集成

软考高项笔记 | 软件集成技术

Soft test high item notes | contents of project proposal

idea设置services窗口显示树状服务
随机推荐
uniapp处理强制刷新问题
Notes on soft test high items | steps of feasibility study
软考高项笔记 | 信息系统安全
软考高项笔记 | 立项管理内容
软考高项笔记 | 企业应用集成
软考高项笔记 | 项目管理知识体系构成
idea设置services窗口显示树状服务
Soft test high item notes | PERT three-point estimation
邮箱格式测试
软考高项笔记 | 收集需求的工具与技术
Durable and easy to drive are recognized. On the first anniversary of ID. crozz, the power of new products has become stronger?
Uniapp handles forced refresh
ESP32以太网吞吐性能峰值挑战测试笔记
软考高项笔记 | 项目的特点
The security configuration method of remote terminal service (3389) does not need public network IP, and realizes external network access to remote desktop in three steps
Multithreading notes | six states of threads
S7-1500 specific methods and steps of data exchange between CPU and OPC UA server through OPC UA client
L1-002 打印沙漏 (20 分)
软考高项笔记 | 项目建议书的内容
持续有效的风险指标:动荡指数