← Back to DSA
#226

Invert Binary Tree

Invert Binary Tree solution for LeetCode 226, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.

Easy
TreeDepth-First SearchBreadth-First SearchBinary Tree
Solve on LeetCode ↗

Invert Binary Tree

Why it belongs on this sheet

This is short, but it tells you whether binary-tree recursion already feels natural.

Pattern

Swap and recurse

Approach

For each node, swap its children and recursively invert both subtrees.

Java solution

class Solution {
  public TreeNode invertTree(TreeNode root) {
    if (root == null) {
      return null;
    }

    TreeNode temp = root.left;
    root.left = invertTree(root.right);
    root.right = invertTree(temp);
    return root;
  }
}

Complexity

  • Time: O(n)
  • Space: O(h)

Interview note

It is often safer to store one child in a temporary variable before recursive calls.

Dynamic Programming

7 DP Patterns > 100 LeetCode Questions

Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.

7 patternsProgress tracking
Read 7 patterns (5 min)