Problem Statement

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

Example 1:

            4                           4
                        ---->
    2               7           7               2
1       3       6       9   9       6       3       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: []

Key Insights

If you can swap every node’s left and right children, you can “invert” the binary tree. Once you see this, all you need to do is implement a simple post order binary tree traversal. The recursive and iterative approaches are shown below.

Recursive Implementation

# 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

from typing import Optional
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # Handle null root case
        if not root:
            return root
        
        if root.left:
            self.invertTree(root.left)

        if root.right:
            self.invertTree(root.right)

        # Swap left and right children
        root.left, root.right = root.right, root.left

        return root

Iterative Implementation

# 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

from collections import deque
from typing import Optional
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # Handle null root case
        if not root:
            return root

        queue = deque([root])

        while queue:
            node = queue.popleft()

            if node.left:
                queue.append(node.left)

            if node.right:
                queue.append(node.right)

            # Swap left and right children
            node.left, node.right = node.right, node.left
        
        return root

Leetcode 226 Invert Binary Tree