-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path121-avl_insert.c
112 lines (95 loc) · 1.84 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "binary_trees.h"
/**
* check_balance - checks the balance of each node
* @node: pointer to the node
* @value: input value
*
* Return: no return
*/
void check_balance(avl_t **node, int value)
{
int balance;
balance = binary_tree_balance(*node);
if (balance > 1 && value < (*node)->left->n)
{
*node = binary_tree_rotate_right(*node);
return;
}
if (balance < -1 && value > (*node)->right->n)
{
*node = binary_tree_rotate_left(*node);
return;
}
if (balance > 1 && value > (*node)->left->n)
{
(*node)->left = binary_tree_rotate_left((*node)->left);
*node = binary_tree_rotate_right(*node);
return;
}
if (balance < -1 && value < (*node)->right->n)
{
(*node)->right = binary_tree_rotate_right((*node)->right);
*node = binary_tree_rotate_left(*node);
return;
}
}
/**
* avl_in - checks if node is inserted
* @tree: tree root
* @value: node value
*
* Return: pointer to the new node
*/
avl_t *avl_in(avl_t **tree, int value)
{
avl_t *node;
if (value < (*tree)->n)
{
if ((*tree)->left == NULL)
{
(*tree)->left = binary_tree_node(*tree, value);
return ((*tree)->left);
}
else
{
node = avl_in(&((*tree)->left), value);
if (node)
check_balance(tree, value);
return (node);
}
}
if (value > (*tree)->n)
{
if ((*tree)->right == NULL)
{
(*tree)->right = binary_tree_node(*tree, value);
return ((*tree)->right);
}
else
{
node = avl_in(&((*tree)->right), value);
if (node)
check_balance(tree, value);
return (node);
}
}
return (NULL);
}
/**
* avl_insert - inserts a value in a AVL Tree
* @tree: tree root
* @value: node value
*
* Return: pointer to the new node
*/
avl_t *avl_insert(avl_t **tree, int value)
{
avl_t *node;
if (*tree == NULL)
{
*tree = binary_tree_node(NULL, value);
return (*tree);
}
node = avl_in(tree, value);
return (node);
}