Data Structures · Visualization
BST: Delete
Binary Search Tree
Deleting from a BST has three cases depending on the node's children. Time: O(h), O(log n) average, O(n) worst case. Space: O(h) recursive, O(1) iterative.
Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.
BST: Delete
Binary Search TreeDeleting from a BST has three cases depending on the node's children. A leaf (no children) is simply removed. A node with one child is replaced by that child. A node with two children is trickier: it's replaced by its 'in-order successor' (the smallest value in its right subtree), which preserves the BST ordering rule, and then that successor is removed from its original spot.
How Delete Works
- Find the node to delete by searching as usual.
- If it has no children, remove it directly.
- If it has exactly one child, replace the node with that child.
- If it has two children, find the in-order successor (smallest value in the right subtree), copy its value into the node, then delete the successor from the right subtree (which will have at most one child).
Delete Worked Example
Input: Delete 3 (two children: 1 and 6) from root(8) -> left(3) -> left(1), right(6)
- Node 3 has two children
- Find in-order successor: smallest value in 3's right subtree, which is 6
- Copy 6 into node 3's position
- Remove the original node 6 (it had no children)
Output: 8 / 6 / 1
Press ▶ Run to watch it step by step.
def min_value(n):
while n.left:
n = n.left
return n.val
def delete(root, val):
if not root:
return None
if val < root.val:
root.left = delete(root.left, val)
elif val > root.val:
root.right = delete(root.right, val)
else:
if not root.left:
return root.right # one child
if not root.right:
return root.left
root.val = min_value(root.right) # successor
root.right = delete(root.right, root.val)
return root
# example: delete 3Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Delete Time & Space Complexity
When to Use Delete
- Removing an entry from a sorted, searchable collection
- Maintaining accurate ranking/leaderboard data as entries drop out
- Database index maintenance when records are deleted
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.