Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function remove(data, node, parent):
- if node is null:
- return null // Base case: data not found
- // Traverse the tree
- if data < node.data:
- // Move to the left child
- node.left = remove(data, node.left, node)
- else if data > node.data:
- // Move to the right child
- node.right = remove(data, node.right, node)
- else:
- // Node found
- if node.left is null and node.right is null:
- // Case 1: No children (leaf node)
- if parent is null:
- return null // Tree becomes empty
- if parent.left == node:
- parent.left = null // Remove reference from parent
- else:
- parent.right = null // Remove reference from parent
- else if node.left is null:
- // Case 2: One child (right)
- if parent is null:
- return node.right // Update root
- if parent.left == node:
- parent.left = node.right // Replace with right child
- else:
- parent.right = node.right // Replace with right child
- else if node.right is null:
- // Case 2: One child (left)
- if parent is null:
- return node.left // Update root
- if parent.left == node:
- parent.left = node.left // Replace with left child
- else:
- parent.right = node.left // Replace with left child
- else:
- // Case 3: Two children
- predecessor = findMax(node.left) // Find the predecessor
- node.data = predecessor.data // Copy predecessor's value to node
- node.left = remove(predecessor.data, node.left, node) // Remove predecessor
- return node // Return the updated node
- function findMax(node):
- while node.right is not null:
- node = node.right
- return node // Return the node with the maximum value
Advertisement
Add Comment
Please, Sign In to add comment