Tensorum
LeetCode 226 · DFS Basics

Invert Binary Tree

LeetCode 226 · Easy · solution, intuition & step-by-step walkthrough

Swap children at every node.

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
0 msruntime · beats 100%
19.3 MBmemory · beats 32%
1approach
8accepted runs · last 16 Mar 2026

This is how I solved Invert Binary Tree (LeetCode 226), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.

Approach

  1. 1

    Empty → None.

  2. 2

    Invert left and right subtrees.

  3. 3

    Swap root.left and root.right; return root.

How I solved it

Recursive swapPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
            if root == None:
                return None
            self.invertTree(root.left)
            self.invertTree(root.right)
            root.left,root.right=root.right,root.left
            return root
Loading the step-through…

Invert Binary Tree — FAQ

What is the intuition behind Invert Binary Tree?

Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.

How do you solve Invert Binary Tree (LeetCode 226)?

1. Empty → None. 2. Invert left and right subtrees. 3. Swap root.left and root.right; return root.

What is the time and space complexity of Invert Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: Recursive swap.)

What are common mistakes in Invert Binary Tree?

Order doesn't matter — pre-order swapping works too.