forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Convert sorted array to binary search tree
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
39261d2
commit d7b492a
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test bst_convert.c |
45 changes: 45 additions & 0 deletions
45
108_convert_sorted_array_to_binary_search_tree/bst_convert.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
|
||
struct TreeNode { | ||
int val; | ||
struct TreeNode *left; | ||
struct TreeNode *right; | ||
}; | ||
|
||
static void recursive(struct TreeNode **node, int *nums, int size, int i, struct TreeNode **root) | ||
{ | ||
if () { | ||
*node = malloc(sizeof(**node)); | ||
(*node)->val = nums[ | ||
} else { | ||
recursive(node, nums, size, i, root); | ||
*node = malloc(sizeof(**root)); | ||
if (i == size / 2) { | ||
*root = *node; | ||
} | ||
recursive(node, nums, size, i, root); | ||
} | ||
} | ||
|
||
static struct TreeNode* sortedArrayToBST(int* nums, int numsSize) | ||
{ | ||
if (numsSize == 0) { | ||
return NULL; | ||
} | ||
struct TreeNode *node, *root; | ||
recursive(nums, numsSize, 0, &root); | ||
return root; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
int i, count = argc - 1; | ||
int *nums = malloc(count * sizeof(int)); | ||
for (i = 0; i < count; i++) { | ||
nums[i] = atoi(argv[i + 1]); | ||
} | ||
sortedArrayToBST(nums, count); | ||
return 0; | ||
} |