-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAVL.py
144 lines (125 loc) · 2.23 KB
/
AVL.py
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'Self-balancing binary search tree'
__author__ = 'lxp'
#《大话数据结构》335页
class BiTNode(object):
def __init__(self):
self.data = None
self.bf = 0
self.lchild = None
self.rchild = None
def r_Rotate(p):
L = p.lchild
p.lchild = L.rchild
L.rchild = p
return L
def l_Rotate(p):
R = p.rchild
p.rchild = R.lchild
R.lchild = p
return R
def leftBalance(T):
L = T.lchild
if L.bf == 1:
T.bf = L.bf = 0
T = r_Rotate(T)
elif L.bf == -1:
Lr = L.rchild
if Lr.bf == 1:
T.bf = -1
L.bf = 0
elif Lr.bf == 0:
L.bf = 0
T.bf = 0
else:
L.bf = 1
T.bf = 0
Lr.bf = 0
T.lchild = l_Rotate(T.lchild)
T = r_Rotate(T)
return T
def rightBalance(T):
R = T.rchild
if R.bf == -1:
T.bf = R.bf = 0
T = l_Rotate(T)
if R.bf == 1:
Rl = R.lchild
if Rl.bf == -1:
T.bf = 1
R.bf = 0
elif Rl.bf == 0:
T.bf = 0
R.bf = 0
else:
R.bf = -1
T.bf = 0
Rl.bf = 0
T.rchild = r_Rotate(T.rchild)
T = l_Rotate(T)
return T
def insertAVL(T, e, taller, mark):
if not T:
T = BiTNode()
T.data = e
T.bf = 0
taller = True
else:
if e == T.data:
taller = False
return T, e, taller, False
if e < T.data:
T.lchild, e, taller, mark = insertAVL(T.lchild, e, taller, mark)
if not mark:
return T, e, taller, False
if taller:
if T.bf == 1:
T = leftBalance(T)
taller = False
elif T.bf == 0:
T.bf = 1
taller = True
else:
T.bf = 0
taller = False
else:
T.rchild, e, taller, mark = insertAVL(T.rchild, e, taller, mark)
if not mark:
return T, e, taller, False
if taller:
if T.bf == 1:
T.bf = 0
taller = False
elif T.bf == 0:
T.bf = -1
taller = True
else:
T = rightBalance(T)
taller = False
return T, e, taller, True
def showTree(T):
if not T:
print("树为空树")
return
L = [T]
while len(L) != 0:
print(L[0].data, ',', end = '')
if L[0].lchild:
L.append(L[0].lchild)
if L[0].rchild:
L.append(L[0].rchild)
del L[0]
print()
return
#test
def test():
L = [5, 6, 7, 3, 4, 10, 9, 8, 2, 1]
T = None
for i in L:
T, e, taller, mark = insertAVL(T, i, False, False)
showTree(T)
#showTree(T)
return
if __name__ == '__main__':
test()