-
Notifications
You must be signed in to change notification settings - Fork 0
/
121-avl_insert.c
71 lines (68 loc) · 1.77 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
#include "binary_trees.h"
/**
* r_insert_node - node value instertion in a AVL.
* @tree: type **pointer of root node of the AVL tree struct.
* @parent: parent node of struct AVL.
* @new: type**pointer left or right insertion.
* @nval: insertion value of the AVL.
* Return: pointer to the new root after insertion otherwise NULL
*/
avl_t *r_insert_node(avl_t **tree, avl_t *parent, avl_t **new, int nval)
{
int bval;
if (*tree == NULL)
return (*new = binary_tree_node(parent, nval));
if ((*tree)->n > nval)
{
(*tree)->left = r_insert_node(&(*tree)->left, *tree, new, nval);
if ((*tree)->left == NULL)
return (NULL);
}
else if ((*tree)->n < nval)
{
(*tree)->right = r_insert_node(&(*tree)->right, *tree, new, nval);
if ((*tree)->right == NULL)
return (NULL);
}
else
{
return (*tree);
}
bval = binary_tree_balance(*tree);
if (bval > 1 && (*tree)->left->n > nval)
{
*tree = binary_tree_rotate_right(*tree);
}
else if (bval > 1 && (*tree)->left->n < nval)
{
(*tree)->left = binary_tree_rotate_left((*tree)->left);
*tree = binary_tree_rotate_right(*tree);
}
else if (bval < -1 && (*tree)->right->n < nval)
{
*tree = binary_tree_rotate_left(*tree);
}
else if (bval < -1 && (*tree)->right->n > nval)
{
(*tree)->right = binary_tree_rotate_right((*tree)->right);
*tree = binary_tree_rotate_left(*tree);
}
return (*tree);
}
/**
* avl_insert - inserts a value into an AVL tree.
* @tree: type **pointer to the root node of the AVL tree to insert into.
* @value: value to store in the node to be inserted
* Return: inserted node, or NULL if fails.
*/
avl_t *avl_insert(avl_t **tree, int value)
{
avl_t *new = NULL;
if (*tree == NULL)
{
*tree = binary_tree_node(NULL, value);
return (*tree);
}
r_insert_node(tree, *tree, &new, value);
return (new);
}