-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path124-sorted_array_to_avl.c
executable file
·49 lines (45 loc) · 1.24 KB
/
124-sorted_array_to_avl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "binary_trees.h"
avl_t *sorted_array_to_avl(int *array, size_t size);
avl_t *aux_sort(avl_t *parent, int *array, int begin, int last);
/**
* sorted_array_to_avl - Builds an AVL tree from an array.
*
* @array: A pointer to the first element of the array to be converted.
* @size: The number of element in the array
*
* Return: A pointer to the root node of the created AVL tree, NULL on failure.
*/
avl_t *sorted_array_to_avl(int *array, size_t size)
{
if (array == NULL || size == 0)
return (NULL);
return (aux_sort(NULL, array, 0, ((int)(size)) - 1));
}
/**
* aux_sort - Create the tree using the half element of the array.
*
* @parent: Parent of the node to create.
* @array: Sorted array.
* @begin: Position where the array starts.
* @last: Position where the array ends.
*
* Return: Tree created.
*/
avl_t *aux_sort(avl_t *parent, int *array, int begin, int last)
{
avl_t *root;
binary_tree_t *aux;
int mid = 0;
if (begin <= last)
{
mid = (begin + last) / 2;
aux = binary_tree_node((binary_tree_t *)parent, array[mid]);
if (aux == NULL)
return (NULL);
root = (avl_t *)aux;
root->left = aux_sort(root, array, begin, mid - 1);
root->right = aux_sort(root, array, mid + 1, last);
return (root);
}
return (NULL);
}