안선생의 개발 블로그

AVL Tree 본문

알고리즘

AVL Tree

안선생 2022. 11. 27. 16:42
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 <iostream>
using namespace std;
 
struct Node
{
    Node* lchild;
    int data;
    int height;
    Node* rchild;
}*root = NULL;
 
int NodeHeight(Node* p)
{
    int hl, hr;
 
    hl = p && p->lchild ? p->lchild->height : 0;
    hr = p && p->rchild ? p->rchild->height : 0;
 
    return hl > hr ? hl + 1 : hr + 1;
}
 
int Balance(Node* p)
{
    int hl, hr;
 
    hl = p && p->lchild ? p->lchild->height : 0;
    hr = p && p->rchild ? p->rchild->height : 0;
 
    return hl - hr;
}
 
Node* LLRotation(Node* p)
{
    Node* pl = p->lchild;
    Node* plr = pl->rchild;
 
    pl->rchild = p;
    p->lchild = plr;
    p->height = NodeHeight(p);
    pl->height = NodeHeight(pl);
 
    if (root == p)
        root = pl;
 
    return pl;
}
Node* LRRotation(Node* p)
{
    Node* pl = p->lchild;
    Node* plr = pl->rchild;
 
    pl->rchild = plr->lchild;
    p->lchild = plr->rchild;
 
    plr->lchild = pl;
    plr->rchild = p;
 
    pl->height=NodeHeight(pl);
    p->height = NodeHeight(p);
    plr->height = NodeHeight(plr);
    if (root == p)
        root = plr;
    return plr;
}
Node* RRRotation(Node* p)
{
    return NULL;
}
Node* RLRotation(Node* p)
{
    return NULL;
}
Node* Rinsert(Node* p, int key)
{
    Node* t = NULL;
    if (p == NULL)
    {
        t = new Node;
        t->data = key;
        t->height = 1;
        t->lchild = t->rchild = NULL;
        return t;
    }
    if (key < p->data)
        p->lchild = Rinsert(p->lchild, key);
    else if (key > p->data)
        p->rchild = Rinsert(p->rchild, key);
 
    p->height = NodeHeight(p);
 
    if (Balance(p) == 2 && Balance(p->lchild) == 1)
        return LLRotation(p);
    else if (Balance(p) == 2 && Balance(p->lchild) == -1)
        return LRRotation(p);
    else if (Balance(p) == -2 && Balance(p->rchild) == -1)
        return RRRotation(p);
    else if (Balance(p) == -2 && Balance(p->rchild) == 1)
        return RLRotation(p);
    return p;
}
 
int main()
{
 
    //root = Rinsert(root, 10);
    //Rinsert(root, 5);
    //Rinsert(root, 7);
    
 
    
     return 0;
cs

'알고리즘' 카테고리의 다른 글

heap  (0) 2022.11.27
BST  (0) 2022.11.27
메트릭스2  (0) 2022.11.27
C++ 메트릭스  (0) 2022.11.27
C++ tree  (0) 2022.11.16