Invert Binary Tree
LeetCode 226 · Easy · solution, intuition & step-by-step walkthrough
Swap children at every node.
This is how I solved Invert Binary Tree (LeetCode 226), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.
Approach
- 1
Empty → None.
- 2
Invert left and right subtrees.
- 3
Swap root.left and root.right; return root.
How I solved it
Recursive swapPythonO(n) time · O(h) space
# 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 root == None:
return None
self.invertTree(root.left)
self.invertTree(root.right)
root.left,root.right=root.right,root.left
return rootInvert Binary Tree — FAQ
What is the intuition behind Invert Binary Tree?
Mirroring a tree means swapping every node's left and right children. Do it recursively: invert both subtrees, then swap them.
How do you solve Invert Binary Tree (LeetCode 226)?
1. Empty → None. 2. Invert left and right subtrees. 3. Swap root.left and root.right; return root.
What is the time and space complexity of Invert Binary Tree?
Time: O(n). Space: O(h). (Accepted approach: Recursive swap.)
What are common mistakes in Invert Binary Tree?
Order doesn't matter — pre-order swapping works too.