题目:给你一个整数数组 nums
,其中元素已经按 升序 排列,请你将其转换为一棵
平衡二叉搜索树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//构建平衡二叉搜索树:每次选择最中间的作为当前节点
struct TreeNode* createval(int* nums,int left,int right)
{
if(left>right)
return NULL;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
int mid = (left + right)/2;
root->val=nums[mid];
root->left = createval(nums,left,mid-1);
root->right = createval(nums,mid+1,right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
int left = 0;
int right = numsSize-1;
if(numsSize==0)
return NULL;
return createval(nums,left,right);
}