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 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. 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

  1. If the current node is null, return (base case).
  2. Swap the current node's left and right child pointers.
  3. Recursively invert the (new) left subtree.
  4. Recursively invert the (new) right subtree.

Mirror / Invert Worked Example

Input: Tree: root(1) -> left(2), right(3)

  1. Swap root's children: left becomes 3, right becomes 2
  2. Recurse into subtree 3 (was root.left): no children to swap
  3. Recurse into subtree 2 (was root.right): no children to swap

Output: 1 / \ 3 2

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
def mirror(root):
    if not root:
        return None
    root.left, root.right = mirror(root.right), mirror(root.left)
    return root
# example: mirror
Input: Tree: root(1) -> left(2), right(3)

Behind 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

TimeO(n)
SpaceO(h) for the recursion stack

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.