/
124-sorted_array_to_avl.c
40 lines (39 loc) · 1.01 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
#include "binary_trees.h"
/**
* 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);
}
/**
* sorted_array_to_avl - create a alv tree from sorted array
* @array: sorted array
* @size: size of the sorted array
* Return: alv tree form sorted array
*/
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));
}