-
Notifications
You must be signed in to change notification settings - Fork 3
/
124-sorted_array_to_avl.c
63 lines (51 loc) · 1.36 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "binary_trees.h"
/**
* create_tree - creates an AVL tree with recursion
*
* @node: pointer node
* @array: input array of integers
* @size: size of array
* @mode: 1 to adding on the left, 2 to adding on the right
* Return: no return
*/
void create_tree(avl_t **node, int *array, size_t size, int mode)
{
size_t middle;
if (size == 0)
return;
middle = (size / 2);
middle = (size % 2 == 0) ? middle - 1 : middle;
if (mode == 1)
{
(*node)->left = binary_tree_node(*node, array[middle]);
create_tree(&((*node)->left), array, middle, 1);
create_tree(&((*node)->left), array + middle + 1, (size - 1 - middle), 2);
}
else
{
(*node)->right = binary_tree_node(*node, array[middle]);
create_tree(&((*node)->right), array, middle, 1);
create_tree(&((*node)->right), array + middle + 1, (size - 1 - middle), 2);
}
}
/**
* sorted_array_to_avl - creates root node and calls to create_tree
*
* @array: input array of integers
* @size: size of array
* Return: pointer to the root
*/
avl_t *sorted_array_to_avl(int *array, size_t size)
{
avl_t *root;
size_t middle;
root = NULL;
if (size == 0)
return (NULL);
middle = (size / 2);
middle = (size % 2 == 0) ? middle - 1 : middle;
root = binary_tree_node(root, array[middle]);
create_tree(&root, array, middle, 1);
create_tree(&root, array + middle + 1, (size - 1 - middle), 2);
return (root);
}