当前位置:网站首页>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
边栏推荐
- L2-023 graph coloring problem (25 points) (graph traversal)
- web页面如何渲染
- Complete binary search tree (30 points)
- A must see wechat applet development guide 1 - basic knowledge
- How to read excel table to database
- SAP 101K 411K 库存变化
- Solidity 问题汇总
- 是否同一棵二叉搜索树 (25 分)
- Trc20 fund collection solution based on thinkphp5 version
- Program, process, thread; Memory structure diagram; Thread creation and startup; Common methods of thread
猜你喜欢
Brush classic topics
MySQL小练习(仅适合初学者,非初学者勿进)
Experimental report on analysis of overflow vulnerability of assembly language and reverse engineering stack
A must see wechat applet development guide 1 - basic knowledge
[C language] document operation
Multi view depth estimation by fusing single view depth probability with multi view geometry
The K neighbors of each sample are obtained by packet switching
2021 Li Hongyi's adaptive learning rate of machine learning
OneFlow学习笔记:从Functor到OpExprInterpreter
2022-04-22 openebs cloud native storage
随机推荐
论文阅读《Multi-View Depth Estimation by Fusing Single-View Depth Probability with Multi-View Geometry》
Single chip microcomputer nixie tube stopwatch
Search tree judgment (25 points)
GoLand debug go use - white record
Flink同时读取mysql与pgsql程序会卡住且没有日志
基于ThinkPHP5版本TRC20-资金归集解决方案
DJ music management software pioneer DJ rekordbox
L2-022 重排链表 (25 分)(map+结构体模拟)
搜索树判断 (25 分)
Common errors of VMware building es8
根据后序和中序遍历输出先序遍历 (25 分)
Go language self-study series | initialization of golang structure
About CIN, scanf and getline, getchar, CIN Mixed use of getline
Play with binary tree (25 points)
Whether the same binary search tree (25 points)
Share the office and improve the settled experience
SAP 101K 411K 库存变化
Non duplicate data values of two MySQL query tables
Valgrind and kcache grind use run analysis
Group Backpack