Skip to content

Commit 9bbc4d9

Browse files
committed
Update AVLtree.py
add comments
1 parent d1dba51 commit 9bbc4d9

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

data_structures/binary tree/AVLtree.py

+32-8
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ def setheight(self,height):
5353
return
5454

5555
def getheight(node):
56-
# print("xxx")
5756
if node is None:
5857
return 0
5958
return node.getheight()
@@ -66,6 +65,17 @@ def my_max(a,b):
6665

6766

6867
def leftrotation(node):
68+
'''
69+
A B
70+
/ \ / \
71+
B C Bl A
72+
/ \ --> / / \
73+
Bl Br UB Br C
74+
/
75+
UB
76+
77+
UB = unbalanced node
78+
'''
6979
print("left rotation node:",node.getdata())
7080
ret = node.getleft()
7181
node.setleft(ret.getright())
@@ -77,6 +87,9 @@ def leftrotation(node):
7787
return ret
7888

7989
def rightrotation(node):
90+
'''
91+
a mirror symmetry rotation of the leftrotation
92+
'''
8093
print("right rotation node:",node.getdata())
8194
ret = node.getright()
8295
node.setright(ret.getleft())
@@ -87,24 +100,35 @@ def rightrotation(node):
87100
ret.setheight(h2)
88101
return ret
89102

103+
def rlrotation(node):
104+
'''
105+
A A Br
106+
/ \ / \ / \
107+
B C RR Br C LR B A
108+
/ \ --> / \ --> / / \
109+
Bl Br B UB Bl UB C
110+
\ /
111+
UB Bl
112+
RR = rightrotation LR = leftrotation
113+
'''
114+
node.setleft(rightrotation(node.getleft()))
115+
return leftrotation(node)
116+
90117
def lrrotation(node):
91118
node.setright(leftrotation(node.getright()))
92119
return rightrotation(node)
93120

94-
def rlrotation(node):
95-
node.setleft(rightrotation(node.getleft()))
96-
return leftrotation(node)
97121

98122
def insert_node(node,data):
99123
if node is None:
100124
return my_node(data)
101125
if data < node.getdata():
102126
node.setleft(insert_node(node.getleft(),data))
103-
if getheight(node.getleft()) - getheight(node.getright()) == 2:
104-
if data < node.getleft().getdata():
127+
if getheight(node.getleft()) - getheight(node.getright()) == 2: #an unbalance detected
128+
if data < node.getleft().getdata(): #new node is the left child of the left child
105129
node = leftrotation(node)
106130
else:
107-
node = rlrotation(node)
131+
node = rlrotation(node) #new node is the right child of the left child
108132
else:
109133
node.setright(insert_node(node.getright(),data))
110134
if getheight(node.getright()) - getheight(node.getleft()) == 2:
@@ -178,7 +202,7 @@ def del_node(self,data):
178202
print("Tree is empty!")
179203
return
180204
self.root = del_node(self.root,data)
181-
def traversale(self):
205+
def traversale(self): #a level traversale, gives a more intuitive look on the tree
182206
q = my_queue()
183207
q.push(self.root)
184208
layer = self.getheight()

0 commit comments

Comments
 (0)