📚 PracticeEasyAlgorithm ProblemCoding Ready

Invert Binary Tree

treedfsrecursion
LeetCode #226
Updated Dec 20, 2025

Question

Given the root of a binary tree, invert the tree, and return its root.

Inverting means swapping the left and right children of all nodes.

LeetCode: Invert Binary Tree

Example:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

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

Fun fact: This is the famous problem that Max Howell (creator of Homebrew) allegedly couldn't solve in a Google interview.

Hints

Hint 1

Think recursively: to invert a tree, swap its children, then invert each subtree.

Hint 2

You can swap the children before or after recursing - both work!

Hint 3

Be careful with Python's tuple unpacking for swapping: root.left, root.right = root.right, root.left


Your Solution

python
Auto-saves every 30s

Try solving the problem first before viewing the solution


0:00time spent