108. Convert Sorted Array to Binary Search Tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a height balanced binary search tree.
 

Example 1:

LeetCode //C - 108. Convert Sorted Array to Binary Search Tree-LMLPHP

LeetCode //C - 108. Convert Sorted Array to Binary Search Tree-LMLPHP

Example 2:

LeetCode //C - 108. Convert Sorted Array to Binary Search Tree-LMLPHP

Constraints:
  • 1 <= nums.length <= 1 0 4 10^4 104
  • - 1 0 4 < = n u m s [ i ] < = 1 0 4 10^4 <= nums[i] <= 10^4 104<=nums[i]<=104
  • nums is sorted in a strictly increasing order.

From: LeetCode
Link: 108. Convert Sorted Array to Binary Search Tree


Solution:

Ideas:
  1. The helper function is used to convert a subarray defined by the start and end indices into a subtree of the BST.
  2. If start > end, it means the subarray is empty and we return NULL.
  3. We calculate the middle index of the subarray and use the element at that index to create a new tree node.
  4. The left and right children of this new node are recursively determined by the left and right halves of the subarray.
  5. The sortedArrayToBST function is just an entry point that calls the helper function using the entire array as the initial subarray.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* helper(int* nums, int start, int end) {
    if (start > end) {
        return NULL;
    }
    
    int mid = start + (end - start) / 2;
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = nums[mid];
    node->left = helper(nums, start, mid - 1);
    node->right = helper(nums, mid + 1, end);
    
    return node;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
    return helper(nums, 0, numsSize - 1);
}
10-16 03:00