- 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