Day 6 - Invert Binary Tree

Our first look at trees!

🌳 Problem:

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

Inversion means swapping every left and right subtree, recursively.

πŸ“˜ Examples:

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

Example 2
Input: root = [2,1,3]
Output: [2,3,1]

Example 3
Input: root = []
Output: []

πŸ“ Constraints:

  • The number of nodes is in the range [0, 100]

  • -100 <= Node.val <= 100

🧠 How to Approach It

There are two main strategies:

  1. Recursive Depth-First Search (DFS) β€” simple and elegant

  2. Iterative BFS (with a queue) β€” if you want to avoid recursion stack limits

Here we use DFS, and for each node:

  • Swap the left and right children

  • Then recurse on both children

This problem is sometimes jokingly called the "Hello World" of binary tree problems β€” clean, visual, and satisfying.

βœ… Python Solution:

# 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 not root:
            return None
        
        # Swap left and right
        temp = root.left
        root.left = root.right
        root.right = temp

        # Recurse
        self.invertTree(root.left)
        self.invertTree(root.right)

        return root

🧡 TL;DR:

  • πŸ” Swap left and right children at every node

  • πŸ”½ DFS recursive solution works cleanly

  • 🌲 Post-inversion, the tree becomes its own mirror