Data Structures · Visualization
Binary Tree: Delete
Binary Tree
Deleting a node from a general binary tree (keeping it complete/balanced in shape) involves three steps: find the node to delete, find the very last node in level order, copy that last node's value into the node to delete, and then remove the last node. Time: O(n) to locate both the target and the last node. Space: O(n) worst case for the traversal queue/stack.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Delete
Binary TreeDeleting a node from a general binary tree (keeping it complete/balanced in shape) involves three steps: find the node to delete, find the very last node in level order, copy that last node's value into the node to delete, and then remove the last node. This keeps the tree's shape compact.
How Delete Works
- Find the node containing the target value using a traversal.
- Find the deepest, rightmost node in the tree (the last node in level order).
- Copy the last node's value into the target node.
- Remove the last node from its original position.
Delete Worked Example
Input: Delete 5 from root(10) -> left(5), right(7)
- Target node found: 5 (root's left child)
- Deepest rightmost node is 7
- Copy 7's value into the target node: root.left becomes 7
- Remove the original node 7
Output: 10 / \ 7 (empty)
Press ▶ Run to watch it step by step.
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: # found
if not root.left:
return root.right
if not root.right:
return root.left
# two children: replace with successor
succ = root.right
while succ.left:
succ = succ.left
root.val = succ.val
root.right = delete(root.right, succ.val)
return root
# example: delete 5Behind 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 item from a complete-tree-based structure like a heap
- Maintaining a compact tree shape after removals
- General tree maintenance where order does not matter, only structure
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.