Data Structures & Algorithms Binary Trees
💡
Exercise 91

Invert Binary Tree 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Invert a binary tree — swap every left and right child. This is the famous problem that "Homebrew's creator Max Howell couldn't solve at Google."

# Before: 4 After: 4 # / \ / \ # 2 7 → 7 2 # / \ / \ / \ / \ # 1 3 6 9 9 6 3 1

The simplest recursive solution:

  • Base case: If node is None, return None
  • Swap: Switch left and right children
  • Recurse: Invert both subtrees
  • Time: O(n), Space: O(h)

This is a great example of how elegant recursion can be — just 3 lines of code!

📋 Instructions
Implement `invert_tree(root)` and verify by doing an inorder traversal before and after inversion.
Recursion! Base case: if root is None, return None. Swap left and right children: root.left, root.right = root.right, root.left. Then recurse on both.
🧪 Test Cases
Input
inorder(root)
Expected
[1, 2, 3, 4, 6, 7, 9]
Test case 1
Input
inorder(root)
Expected
[9, 7, 6, 4, 3, 2, 1]
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.