MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / del_node

Function del_node

data_structures/binary_tree/avl_tree.py:198–242  ·  view source on GitHub ↗
(root: MyNode, data: Any)

Source from the content-addressed store, hash-verified

196
197
198def del_node(root: MyNode, data: Any) -> MyNode | None:
199 left_child = root.get_left()
200 right_child = root.get_right()
201 if root.get_data() == data:
202 if left_child is not None and right_child is not None:
203 temp_data = get_left_most(right_child)
204 root.set_data(temp_data)
205 root.set_right(del_node(right_child, temp_data))
206 elif left_child is not None:
207 root = left_child
208 elif right_child is not None:
209 root = right_child
210 else:
211 return None
212 elif root.get_data() > data:
213 if left_child is None:
214 print("No such data")
215 return root
216 else:
217 root.set_left(del_node(left_child, data))
218 # root.get_data() < data
219 elif right_child is None:
220 return root
221 else:
222 root.set_right(del_node(right_child, data))
223
224 # Re-fetch left_child and right_child references
225 left_child = root.get_left()
226 right_child = root.get_right()
227
228 if get_height(right_child) - get_height(left_child) == 2:
229 assert right_child is not None
230 if get_height(right_child.get_right()) > get_height(right_child.get_left()):
231 root = left_rotation(root)
232 else:
233 root = rl_rotation(root)
234 elif get_height(right_child) - get_height(left_child) == -2:
235 assert left_child is not None
236 if get_height(left_child.get_left()) > get_height(left_child.get_right()):
237 root = right_rotation(root)
238 else:
239 root = lr_rotation(root)
240 height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1
241 root.set_height(height)
242 return root
243
244
245class AVLtree:

Callers 1

del_nodeMethod · 0.85

Calls 14

get_left_mostFunction · 0.85
get_heightFunction · 0.85
left_rotationFunction · 0.85
rl_rotationFunction · 0.85
right_rotationFunction · 0.85
lr_rotationFunction · 0.85
my_maxFunction · 0.85
get_leftMethod · 0.80
get_rightMethod · 0.80
get_dataMethod · 0.80
set_dataMethod · 0.80
set_rightMethod · 0.80

Tested by

no test coverage detected