llllmz

导航

108. 将有序数组转换为二叉搜索树c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* build(int* nums,int head,int tail){
    if(head>tail) return NULL;
    int mid=head+(tail-head)/2;
    struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val=nums[mid];
    root->right=build(nums,mid+1,tail);
    root->left=build(nums,head,mid-1);
    return root;    
}


struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    return build(nums,0,numsSize-1);
}

posted on 2024-03-15 13:35  神奇的萝卜丝  阅读(20)  评论(0)    收藏  举报