← DSA
EASY

Invert Binary Tree

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary tree, invert it — swap every left and right child — and return the new root.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Base case: if root is None, return None.
  2. Recursively invert the left subtree and the right subtree.
  3. Swap root.left and root.right using the inverted results.
  4. Return root.

Complexity

Time: O(n) — Space: O(h) recursion stack, where h is the tree's height

Code

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def invertTree(root: TreeNode | None) -> TreeNode | None:
    if not root:
        return None
    root.left, root.right = invertTree(root.right), invertTree(root.left)
    return root

Code Explanation

How the solution above works, piece by piece.

  1. Base case: an empty subtree inverts to an empty subtree.
  2. invertTree(root.right) and invertTree(root.left) first mirror each child subtree completely.
  3. The tuple assignment then stores the (already inverted) right subtree as the new left and vice versa. Both calls run before either field is overwritten, so nothing is lost.
  4. Return root so the parent can link it back in.
  5. Each node is visited once: O(n) time, O(height) recursion stack.

Visual Walkthrough

Running it on root = [4, 2, 7, 1, 3, 6, 9]:

Tree before and after inversionbefore4271369after: every node's children swapped4729631
Every node swaps its left and right child, at every level, so the whole tree becomes its mirror image. The colours follow the subtrees rooted at 2 and 7 to the other side.
subtree of 2subtree of 7

Video Explanation

NeetCode — Depth First Search, LeetCode 226