- Leetcode Learning System
- Posts
- Day 6 - Invert Binary Tree
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:
Recursive Depth-First Search (DFS) โ simple and elegant
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