From d7b492a97a69042cd8af4b53265d10145ed0cd71 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 23 Oct 2017 09:40:09 +0800 Subject: [PATCH] Convert sorted array to binary search tree Signed-off-by: begeekmyfriend --- .../Makefile | 2 + .../bst_convert.c | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 108_convert_sorted_array_to_binary_search_tree/Makefile create mode 100644 108_convert_sorted_array_to_binary_search_tree/bst_convert.c diff --git a/108_convert_sorted_array_to_binary_search_tree/Makefile b/108_convert_sorted_array_to_binary_search_tree/Makefile new file mode 100644 index 0000000..113460f --- /dev/null +++ b/108_convert_sorted_array_to_binary_search_tree/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_convert.c diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c new file mode 100644 index 0000000..3f249c2 --- /dev/null +++ b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c @@ -0,0 +1,45 @@ +#include +#include + + +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; +}