-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path121-avl_insert.c
74 lines (67 loc) · 1.76 KB
/
121-avl_insert.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
64
65
66
67
68
69
70
71
72
73
74
#include "binary_trees.h"
/**
* check_balance - check if sub tres are balanced
* @tree: pointer to root node
* @value: value added
* Return: void
*/
void check_balance(avl_t **tree, int value)
{
int balance;
balance = binary_tree_balance(*tree);
if (balance > 1 && value < (*tree)->left->n)
(*tree) = binary_tree_rotate_right(*tree);
else if (balance > 1 && value > (*tree)->left->n)
{
(*tree)->left = binary_tree_rotate_left((*tree)->left);
(*tree) = binary_tree_rotate_right((*tree));
}
else if (balance < -1 && value > (*tree)->right->n)
(*tree) = binary_tree_rotate_left((*tree));
else if (balance < -1 && value < (*tree)->right->n)
{
(*tree)->right = binary_tree_rotate_right((*tree)->right);
(*tree) = binary_tree_rotate_left((*tree));
}
}
/**
* avl_insert - inserts a value in an AVL Tree
* @tree: double pointer to the root node of AVL tree for inserting the value
* @value:value to store in the node to be inserted
* Return: pointer to the created node, or NULL on failure
* If the address stored in tree=NULL, the created node becomes the root node.
* The resulting tree after insertion, must be a balanced AVL Tree
*/
avl_t *avl_insert(avl_t **tree, int value)
{
avl_t *current;
if (!tree)
return (NULL);
if (!(*tree))
{
*tree = binary_tree_node(NULL, value);
return (*tree);
}
if (value < (*tree)->n)
{
if (!(*tree)->left)
{
(*tree)->left = binary_tree_node(*tree, value);
return ((*tree)->left);
}
current = avl_insert(&(*tree)->left, value);
}
else if (value > (*tree)->n)
{
if (!(*tree)->right)
{
(*tree)->right = binary_tree_node(*tree, value);
return ((*tree)->right);
}
current = avl_insert(&(*tree)->right, value);
}
else
return (*tree);
check_balance(tree, value);
return (current);
}