-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path121-avl_insert.c
77 lines (68 loc) · 1.63 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
#include "binary_trees.h"
/**
* bst_insert - inserts a value in a Binary Search Tree
* @tree: a double pointer to the root node of the BST to insert the value
* @value: the value to store in the node to be inserted
* Return: A pointer to the created node
* NULL on failure
*/
bst_t *bst_insert(bst_t **tree, int value)
{
bst_t *tmp = *tree;
bst_t *second = NULL;
bst_t *new = binary_tree_node(NULL, value);
if (*tree == NULL)
*tree = new;
while (tmp)
{
second = tmp;
if (value < tmp->n)
tmp = tmp->left;
else if (value > tmp->n)
tmp = tmp->right;
else if (value == tmp->n)
return (NULL);
}
if (second == NULL)
second = new;
else if (value < second->n)
{
second->left = new;
new->parent = second;
}
else
{
second->right = new;
new->parent = second;
}
return (new);
}
/**
* avl_insert - inserts a value in an AVL Tree
* @tree: a double pointer to the root node of the AVL tree
* @value: value to insert
*
* Return: a pointer to the created node
* NULL on failure
*/
avl_t *avl_insert(avl_t **tree, int value)
{
int balance = 0;
avl_t *node = bst_insert(tree, value);
balance = binary_tree_balance(*tree);
if (balance > 1 && value < node->left->n)
return (binary_tree_rotate_right(node));
if (balance < -1 && value > node->right->n)
return (binary_tree_rotate_left(node));
if (balance > 1 && value > node->left->n)
{
node->left = binary_tree_rotate_left(node->left);
return (binary_tree_rotate_right(node));
}
if (balance < -1 && value < node->right->n)
{
node->right = binary_tree_rotate_right(node->right);
return (binary_tree_rotate_left(node));
}
return (node);
}