MCPcopy
hub / github.com/geekcomputers/Python / delete_node

Function delete_node

binary_search_trees/delete_a_node_in_bst.py:7–37  ·  view source on GitHub ↗

This function deletes a node with value val from the BST

(root: Node, val: int)

Source from the content-addressed store, hash-verified

5
6# The above line imports the inorder_successor function from the inorder_successor.py file
7def delete_node(root: Node, val: int) -> Optional[Node]:
8 """This function deletes a node with value val from the BST"""
9
10 # Search in the right subtree
11 if root.data < val:
12 root.right = delete_node(root.right, val)
13
14 # Search in the left subtree
15 elif root.data > val:
16 root.left = delete_node(root.left, val)
17
18 # Node to be deleted is found
19 else:
20 # Case 1: No child (leaf node)
21 if root.left is None and root.right is None:
22 return None
23
24 # Case 2: One child
25 if root.left is None:
26 return root.right
27
28 # Case 2: One child
29 elif root.right is None:
30 return root.left
31
32 # Case 3: Two children
33 # Find the inorder successor
34 is_node: Node = inorder_successor(root.right)
35 root.data = is_node.data
36 root.right = delete_node(root.right, is_node.data)
37 return root

Callers 1

mainFunction · 0.90

Calls 1

inorder_successorFunction · 0.90

Tested by

no test coverage detected