A simple C solution [Accepted] beats 96.46% with 3ms


  • 0
    B
    /**
     * 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;} 
        struct TreeNode *p=(struct TreeNode*)malloc(sizeof(struct TreeNode));
        if(numsSize==1)
        {
            p->val=nums[0];
            p->left=NULL;
            p->right=NULL;
            return p;
        }
        if(numsSize==2)
        {
            p->val=nums[0];
            p->left=NULL;
            p->right=sortedArrayToBST(&nums[1],1);
            return p;
        }
        int temp=numsSize/2;
        p->val=nums[temp];
        p->left=sortedArrayToBST(&nums[0],temp);
        if(temp+1<numsSize)
        {
            p->right=sortedArrayToBST(&nums[temp+1],numsSize-temp-1);
        }else 
        {
            p->right=NULL;
        }
        return p;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.