Skip to content

Commit f278a4e

Browse files
committed
Sync LeetCode submission - Convert Sorted Array to Binary Search Tree (c)
1 parent d67a86e commit f278a4e

File tree

1 file changed

+34
-0
lines changed
  • my-folder/problems/convert_sorted_array_to_binary_search_tree

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* struct TreeNode *left;
6+
* struct TreeNode *right;
7+
* };
8+
*/
9+
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
10+
if (numsSize == 0) {
11+
return 0;
12+
}
13+
14+
struct TreeNode* node = malloc(sizeof(struct TreeNode));
15+
if (numsSize == 1) {
16+
node->val = *nums;
17+
node->left = 0;
18+
node->right = 0;
19+
return node;
20+
}
21+
22+
int half_idx = numsSize / 2;
23+
24+
// Set the middle number to the node's value
25+
node->val = nums[half_idx];
26+
// printArr(nums, half_idx);
27+
// printArr(nums + half_idx + 1, numsSize - (half_idx + 1));
28+
// Sort all numbers up to but not including the middle number
29+
node->left = sortedArrayToBST(nums, half_idx);
30+
// Sort all numbers after the middle number
31+
node->right = sortedArrayToBST(nums + half_idx + 1, numsSize - (half_idx + 1));
32+
33+
return node;
34+
}

0 commit comments

Comments
 (0)