-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.cpp
130 lines (122 loc) · 2.05 KB
/
tree.cpp
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// tree.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
enum balancefactor
{
LEFTHIGH,
EQUAL,
RIGHTHIGH
};
struct balanceTreeNode{
int data;
balancefactor bf;
balanceTreeNode* lc, *rc;
};
void RR(balanceTreeNode** p) {
balanceTreeNode* pleftright;
pleftright = (*p)->lc;
(*p)->lc = pleftright->rc;
*p = pleftright;
// *
// *
// * *
}
void leftBalance(balanceTreeNode ** T) {
balanceTreeNode * L=(*T)->lc, *LR;
if (L->bf==LEFTHIGH)
{
(*T)->bf = L->bf = EQUAL;
RR(T);
}
else
{
LR = L->rc;
switch (LR->bf)
{
case EQUAL:
(*T)->bf = L->bf = EQUAL;
break;
case LEFTHIGH: //想想那种情况会出现t-l-lr->bf
(*T)->bf = RIGHTHIGH;
L->bf = EQUAL;
break;
case RIGHTHIGH:
(*T)->bf = EQUAL;
L->bf = LEFTHIGH;
break;
default:
break;
}
LR->bf = EQUAL;
LR(&(*T)->lc);
RR(T);
}
}
void LR(balanceTreeNode** p) {
balanceTreeNode* prightleft;
prightleft = (*p)->rc;
(*p)->rc=prightleft->lc;
*p = prightleft;
}
bool inserted(balanceTreeNode ** T,int data){
if (*T == NULL)
{
*T = new balanceTreeNode ;
(*T)->data = data;
(*T)->lc = (*T)->rc = NULL;
(*T)->bf = EQUAL;
return true;
//delete T;
}
else
{
if (data==(*T)->data)
return false;
else if (data <= (*T)->data)
{
if (inserted(&((*T)->lc), data) == false)
return false;
else {
switch ((*T)->bf)
{
case LEFTHIGH:
leftBalance(T);
return false;
case EQUAL:
(*T)->bf = LEFTHIGH;
return true;
case RIGHTHIGH:
(*T)->bf = EQUAL;
return false;
default:
break;
}
}
}
else
{
if (inserted(&(*T)->rc,data)==false)
return false;
//child tree does not grow after inserting
else {
switch ((*T)->bf)
{
case LEFTHIGH:
(*T)->bf = EQUAL;
return false;
case EQUAL:
(*T)->bf = RIGHTHIGH;
return true;
case RIGHTHIGH:
RightBalance(T);
return false;
}
}
}
}
}
int main()
{
return 1;
}