如果按一般思路建一个平衡二叉树,非常麻烦。
但是二分查找树就一个平衡二叉树,所有构建二叉查找树就行。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* bulid(int* nums,int head,int tail){
if(head>tail) return NULL;
int mid=(head+tail)/2;
struct TreeNode* temp=(struct TreeNode*)malloc(sizeof(struct TreeNode));
temp->val=nums[mid];
temp->left=bulid(nums,head,mid-1);
temp->right=bulid(nums,mid+1,tail);
return temp;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
if(numsSize<1) return NULL;
int head=0,tail=numsSize-1;
return bulid(nums,head,tail);
}
结果:
标签:TreeNode,struct,temp,nums,int,mid,二叉,108,数组 From: https://www.cnblogs.com/llllmz/p/18058963