Skip to main content
Easy Trees / DFS High frequency

Invert Binary Tree

Open on LeetCode

Approach Summary

Recursively swap left and right children at every node. Post-order or pre-order both work.

Full Solution & Approach

Mirroring a binary tree is textbook recursion: swap the left and right children, then recurse on both. Base case: a null node has nothing to invert, so return null. For a non-null node, swap root.left and root.right, then call invertTree on each — the swap can happen before or after the recursion because the subtrees are treated independently. Because every node is visited exactly once and each visit does O(1) work (a swap), the time is O(n). Space is the recursion depth — O(h) where h is the tree height, worst case O(n) for a skewed tree. The iterative version with a stack performs the same swaps in any order. This warm-up tests your comfort with the tree-recursion pattern before harder DFS problems.

Every node is visited once with constant work — O(n) time. Recursion depth equals the tree height — O(h) space, O(n) worst case for a skewed tree.

Solution Code

Solution

def invert_tree(root):
    if not root:
        return None
    root.left, root.right = invert_tree(root.right), invert_tree(root.left)
    return root

Edge Cases to Watch

  • Empty tree — returns null
  • Single node — children swapped (both null), returns the node
  • Skewed tree — recursion depth equals height; use an iterative stack on very deep trees to avoid stack overflow

How to Recognize This Pattern

  • Mirror a tree
  • Swap children at every node

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(h)

Tags

Tree DFS BFS

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee