给你一个整数数组 nums
,其中元素已经按升序排列,请你将其转换为一棵 平衡二叉搜索树。
示例 1:
输入:nums = [-10,-3,0,5,9] 输出:[0,-3,9,-10,null,5] 解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案
方法:中序遍历,总是选择中间位置左边的数字作为根节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//自己定义的build函数要放在前面
struct TreeNode* build(int* nums,int left,int right){
if(left>right){return NULL;}
int mid=(left+right)/2;
//创建新节点
struct TreeNode* root =(struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=nums[mid];
root->left=build(nums,left,mid-1);
root->right=build(nums,mid+1,right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return build(nums,0,numsSize-1);
}