当前位置:网站首页>108. 将有序数组转换为二叉搜索树
108. 将有序数组转换为二叉搜索树
2022-04-23 09:04:00 【yitahutu79】
给你一个整数数组 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] <= 104
nums 按 严格递增 顺序排列
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
if (numsSize <= 0) return NULL;
int pos = numsSize / 2;
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[pos];
root->left = sortedArrayToBST(nums, pos);
root->right = sortedArrayToBST(nums + pos + 1, numsSize - pos - 1);
return root;
}
版权声明
本文为[yitahutu79]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40713201/article/details/124357406
边栏推荐
- MYCAT configuration
- 爬虫使用xpath解析时返回为空,获取不到相应的元素的原因和解决办法
- PLC point table (register address and point table definition) cracking detection scheme -- convenient for industrial Internet data acquisition
- 玩转二叉树 (25 分)
- Judgment on heap (25 points) two insertion methods
- GoLand debug go use - white record
- I don't understand time, timestamp and time zone. Look at this article
- 还原二叉树 (25 分)
- Brief steps to build a website / application using flash and H5
- Program, process, thread; Memory structure diagram; Thread creation and startup; Common methods of thread
猜你喜欢

调包求得每个样本的k个邻居

L2-024 部落 (25 分)(并查集)

Non duplicate data values of two MySQL query tables
![[58] length of the last word [leetcode]](/img/c5/3ba1fe5a81593d9576bb597f0d5f45.png)
[58] length of the last word [leetcode]

小程序报错:Cannot read property 'currentTarget' of undefined

Introduction to GUI programming swing

Write down the post order traversal of the ~ binary tree

Arbre de dépendance de l'emballage des ressources

Matlab draw five-star red flag

Chris LATTNER, father of llvm: the golden age of compilers
随机推荐
LeetCode_DFS_中等_1254. 统计封闭岛屿的数目
L2-3 romantic silhouette (25 points)
How to read excel table to database
node安装
请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨
Harbor enterprise image management system
资源打包关系依赖树
1099 establish binary search tree (30 points)
Colorui solves the problem of blocking content in bottom navigation
Star Trek's strong attack opens the dream linkage between metacosmic virtual reality
Write down the post order traversal of the ~ binary tree
[indexof] [lastIndexOf] [split] [substring] usage details
完全二叉搜索树 (30 分)
Please arrange star trek in advance to break through the new playing method of chain tour, and the market heat continues to rise
企业微信应用授权/静默登录
MySQL小練習(僅適合初學者,非初學者勿進)
Thread scheduling (priority)
Flink同时读取mysql与pgsql程序会卡住且没有日志
Restore binary tree (25 points)
考研线性代数常见概念、问题总结