Data Structures · Visualization
Binary Tree: Mirror / Invert
Binary Tree
Inverting (mirroring) a tree swaps the left and right children of every node, producing a tree that looks like the original reflected in a mirror. Time: O(n). Space: O(h) for the recursion stack.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Mirror / Invert
Binary TreeInverting (mirroring) a tree swaps the left and right children of every node, producing a tree that looks like the original reflected in a mirror. It is done recursively: swap the current node's children, then recursively invert what are now the left and right subtrees.
How Mirror / Invert Works
- If the current node is null, return (base case).
- Swap the current node's left and right child pointers.
- Recursively invert the (new) left subtree.
- Recursively invert the (new) right subtree.
Mirror / Invert Worked Example
Input: Tree: root(1) -> left(2), right(3)
- Swap root's children: left becomes 3, right becomes 2
- Recurse into subtree 3 (was root.left): no children to swap
- Recurse into subtree 2 (was root.right): no children to swap
Output: 1 / \ 3 2
Press ▶ Run to watch it step by step.
def mirror(root):
if not root:
return None
root.left, root.right = mirror(root.right), mirror(root.left)
return root
# example: mirrorBehind 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.
Mirror / Invert Time & Space Complexity
When to Use Mirror / Invert
- A classic interview question testing recursive tree manipulation
- Producing a mirrored layout for UI display purposes
- Symmetry checks (comparing a tree to its own inverted version)
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.