#226

Invert Binary Tree

Easy Swap children recursively

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Mirror a binary tree by swapping every node's left and right children.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: swap left and right everywhere.

Why this works: invert both subtrees, then swap them.

Example: 4 (2 (1, 3), 7 (6, 9))

→ 4 (7 (9, 6), 2 (3, 1))

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

root.left = invert(root.right); root.right = invert(root.left); — the second line reads the already-changed left.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon