Skip to content

Commit

Permalink
Convert sorted array to binary search tree
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Oct 23, 2017
1 parent 39261d2 commit d7b492a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 108_convert_sorted_array_to_binary_search_tree/Makefile
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 108_convert_sorted_array_to_binary_search_tree/bst_convert.c
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;
}

0 comments on commit d7b492a

Please sign in to comment.