Complete the code to find the node to delete in a BST.
if key < root.val: root.left = deleteNode(root.left, [1]) else: root.right = deleteNode(root.right, key)
To delete a node, we compare the key with the current node's value. If the key is smaller, we move to the left subtree by calling deleteNode with the key.
Complete the code to find the minimum value node in the right subtree during deletion.
def minValueNode(node): current = node while current.[1] is not None: current = current.left return current
The minimum value node in a BST is found by going as far left as possible.
Fix the error in the code that replaces the node's value with the inorder successor's value.
temp = minValueNode(root.[1]) root.val = temp.val root.[2] = deleteNode(root.right, temp.val)
The inorder successor is the minimum node in the right subtree, so we must look at root.right and delete from root.right.
Fill both blanks to handle the case when the node to delete has only one child.
if root.left is None: return root.[1] elif root.[2] is None: return root.left
If the left child is missing, return the right child. If the right child is missing, return the left child.
Fill all three blanks to complete the deletion function for a BST.
def deleteNode(root, key): if root is None: return root if key < root.val: root.left = deleteNode(root.left, [1]) elif key > root.val: root.right = deleteNode(root.right, [2]) else: if root.left is None: return root.[3] elif root.right is None: return root.left temp = minValueNode(root.right) root.val = temp.val root.right = deleteNode(root.right, temp.val) return root
When searching for the node to delete, we pass the key down the tree. If the left child is missing, we return the right child.