Skip to content

Commit 6a79140

Browse files
committed
enhanced del_node function
1 parent 31b6a08 commit 6a79140

File tree

1 file changed

+15
-22
lines changed

1 file changed

+15
-22
lines changed

data_structures/binary_tree/avl_tree.py

+15-22
Original file line numberDiff line numberDiff line change
@@ -195,61 +195,54 @@ def get_left_most(root: MyNode) -> Any:
195195
return root.get_data()
196196

197197

198-
# Function to get balance factor
199198
def get_balance(node: MyNode) -> int:
200199
if node is None:
201200
return 0
202201
return get_height(node.get_left()) - get_height(node.get_right())
203202

204-
205203
def get_min_value_node(node: MyNode) -> MyNode:
206204
current = node
207205
while current.get_left() is not None:
208206
current = current.get_left()
209207
return current
210208

211-
212209
def del_node(root: MyNode, data: Any) -> MyNode | None:
213210
if root is None:
214211
print("Nothing to delete")
215212
return None
216-
213+
217214
if root.get_data() > data:
218215
root.set_left(del_node(root.get_left(), data))
219216
elif root.get_data() < data:
220217
root.set_right(del_node(root.get_right(), data))
218+
elif root.get_left() is None:
219+
return root.get_right()
220+
elif root.get_right() is None:
221+
return root.get_left()
221222
else:
222-
# Node to delete found
223-
if root.get_left() is None:
224-
return root.get_right()
225-
elif root.get_right() is None:
226-
return root.get_left()
227-
else:
228-
# Node with two children
229-
temp = get_min_value_node(root.get_right())
230-
root.set_data(temp.get_data())
231-
root.set_right(del_node(root.get_right(), temp.get_data()))
232-
233-
root.set_height(
234-
1 + my_max(get_height(root.get_left()), get_height(root.get_right()))
235-
)
223+
# Node with two children
224+
temp = get_min_value_node(root.get_right())
225+
root.set_data(temp.get_data())
226+
root.set_right(del_node(root.get_right(), temp.get_data()))
227+
228+
root.set_height(1 + my_max(get_height(root.get_left()), get_height(root.get_right())))
236229

237230
balance = get_balance(root)
238231

239-
# Left Left
232+
# Left Left Case
240233
if balance > 1 and get_balance(root.get_left()) >= 0:
241234
return right_rotation(root)
242235

243-
# Left Right
236+
# Left Right Case
244237
if balance > 1 and get_balance(root.get_left()) < 0:
245238
root.set_left(left_rotation(root.get_left()))
246239
return right_rotation(root)
247240

248-
# Right Right
241+
# Right Right Case
249242
if balance < -1 and get_balance(root.get_right()) <= 0:
250243
return left_rotation(root)
251244

252-
# Right Left
245+
# Right Left Case
253246
if balance < -1 and get_balance(root.get_right()) > 0:
254247
root.set_right(right_rotation(root.get_right()))
255248
return left_rotation(root)

0 commit comments

Comments
 (0)