My Easy C Solution with Comments


  • 0
    R
    struct TreeNode * getNewNode(int data)
    {
        struct TreeNode * root = (struct TreeNode *) malloc(sizeof(struct TreeNode));
        root->val = data;
        root->left = NULL;
        root->right = NULL;
        return root;
    }
    
    struct TreeNode * createTree(int* nums, int start, int end)
    {
        if(start > end) return NULL;
        int mid = (start + end) / 2;
        //assign the middle index element to the root
        struct TreeNode * root = getNewNode(nums[mid]);
        // assign the middle element in the half left subarray as its left child
        root->left = createTree(nums, start, mid-1);
        // assign the middle element in the half right subarray as its right child
        root->right = createTree(nums, mid+1, end);
        return root;
    }
    
    struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
        //pass the first and last index of the array
        return createTree(nums, 0, numsSize - 1);
    }
    

Log in to reply
 

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