Invert Binary Tree

Invert a binary tree (mirror it).

Pattern

Recursive Swap

This problem follows the Recursive Swap pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Recursively swap left and right children of every node.

Key Insight

Swap first, then recurse — or recurse first, then swap. Both work because every node gets visited and swapped exactly once.

Step-by-step

  1. 1Base case: if root is null, return null
  2. 2Swap root.left and root.right
  3. 3Recursively invert the left subtree
  4. 4Recursively invert the right subtree
  5. 5Return root

Pseudocode

def invertTree(root):
    if not root: return null
    root.left, root.right = root.right, root.left
    invertTree(root.left)
    invertTree(root.right)
    return root
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(h)
More Trees Problems

Master this pattern with YeetCode

Practice Invert Binary Tree and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem