-
Notifications
You must be signed in to change notification settings - Fork 2
/
ft_avladd.c
90 lines (81 loc) · 2.44 KB
/
ft_avladd.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_avladd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rlambert <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/11/11 16:42:47 by rlambert #+# #+# */
/* Updated: 2015/04/03 17:21:36 by rlambert ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_avlupdateheight(t_avl *n)
{
n->height = ft_max(ft_avlheight(n->left), ft_avlheight(n->right)) + 1;
}
static void ft_avllrotate(t_avl **node)
{
t_avl *root;
t_avl *pivot;
root = (*node);
pivot = root->right;
root->right = pivot->left;
pivot->left = root;
ft_avlupdateheight(root);
ft_avlupdateheight(pivot);
*node = pivot;
}
static void ft_avlrrotate(t_avl **node)
{
t_avl *root;
t_avl *pivot;
root = (*node);
pivot = root->left;
root->left = pivot->right;
pivot->right = root;
ft_avlupdateheight(root);
ft_avlupdateheight(pivot);
*node = pivot;
}
static void ft_avlrebalance(t_avl **root)
{
int balance;
int lbalance;
int rbalance;
t_avl *n;
n = *root;
balance = n == NULL ? 0 : ft_avlheight(n->left) - ft_avlheight(n->right);
lbalance = (n != NULL && balance > 1) ? ft_avlheight(n->left->left) -
ft_avlheight(n->left->right) : 0;
rbalance = (n != NULL && balance < -1) ? ft_avlheight(n->right->left) -
ft_avlheight(n->right->right) : 0;
if (balance > 1 && lbalance >= 0)
ft_avlrrotate(root);
else if (balance > 1 && lbalance < 0)
{
ft_avllrotate(&n->left);
ft_avlrrotate(root);
}
else if (balance < -1 && rbalance <= 0)
ft_avllrotate(root);
else if (balance < -1 && rbalance > 0)
{
ft_avlrrotate(&n->right);
ft_avllrotate(root);
}
}
void ft_avladd(t_avl **node, t_avl *avl)
{
if (*node == NULL)
{
*node = avl;
return ;
}
if (avl->key < (*node)->key)
ft_avladd(&(*node)->left, avl);
else
ft_avladd(&(*node)->right, avl);
ft_avlupdateheight(*node);
ft_avlrebalance(node);
}