InterviewPrepKit

Home / Coding / Trees

Invert Binary Tree

easy Original ↗
Solving tips
  • Define it recursively: mirror(node) = node whose left is mirror(right) and right is mirror(left); this is a node-local transform so any complete traversal works.
  • Simplest is a 3-line recursive DFS swapping children at every node — O(n) time, O(h) space; know a BFS/stack variant for the 'no recursion' follow-up.
  • Pitfall: use a simultaneous swap (Python tuple assignment or a temp) — sequential root.left = root.right then root.right = root.left loses the original left subtree.
  • Don't overthink traversal order (pre/post/BFS all work) and remember the swap must apply at EVERY node, not just the root's children.

Problem

Given the root of a binary tree, produce its mirror image: at every node, the left and right children swap places. Return the root of the inverted tree (modifying the tree in place is fine).

Examples

Example 1

Input:  root = [4,2,7,1,3,6,9]

        4                 4
       / \               / \
      2   7     →       7   2
     / \ / \           / \ / \
    1  3 6  9         9  6 3  1

Output: [4,7,2,9,6,3,1]

Every left/right pair is swapped, at every depth.

Example 2

Input:  root = [2,1,3]
Output: [2,3,1]

The two leaves trade places under the root.

Example 3

Input:  root = []
Output: []

An empty tree is its own mirror.

Constraints

  • The number of nodes is in [0, 100] — any traversal works; the point is writing it cleanly.
  • -100 <= Node.val <= 100.

Think about it first

Hint 1 What does the mirror of a tree look like in terms of the mirrors of its two subtrees?
Hint 2 Mirror(root) = a node whose left child is Mirror(right subtree) and whose right child is Mirror(left subtree). That sentence is the whole recursion.
Hint 3 Equivalently: visit every node in any order (stack or queue) and swap its two child pointers. The traversal order doesn't matter because each swap is local.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.