Coding Problems
Invert Binary Tree | Leetcode 226
Welcome to our deep dive on Invert Binary Tree (Leetcode 226). This problem is famously meme'd in the CS community ("Max Howell couldn't invert a binary tree on a whiteboard..."). It remains one of the cleanest structural introductions to Tree Traversal and Recursive DFS logic possible.
Problem Statement
Given the root of a binary tree, invert the tree, and return its root.
Inverting a Binary Tree formally means that for every single node in the tree, you seamlessly swap its left and right children explicitly.
Example:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Approach: Recursive DFS (Depth-First Search) O(N)
Recursion thrives on breaking down trees functionally. The core premise is brilliantly simple:
- Base Case: If the
rootisnull, returnnull. There's nothing to recursively invert! - Swap Phase: Grab the
leftchild andrightchild, and swap them completely. - Recursive Leap: Call
invertTreeon the newleftbranch and the newrightbranch.
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# Swap children
root.left, root.right = root.right, root.left
# Invert recursively
self.invertTree(root.left)
self.invertTree(root.right)
return root
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time | O(N) | We visit every single node in the tree exactly once. |
| Space | O(H) | Memory scales based on the height of the tree H due to the recursive call stack. |