Invert Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #226
Mirror a binary tree: swap the left and right child of every node. Return the root.
Examples
text
[4, 2, 7, 1, 3, 6, 9] → [4, 7, 2, 9, 6, 3, 1]
[2, 1, 3] → [2, 3, 1]
[] → []Hints
- Inverting a tree = swap the root's children, then invert each subtree.
- Any traversal order works (pre-, post-, or BFS) as long as each node is swapped once.
Approach
Recursively: if the node is null, return null. Otherwise swap left and right, then invert both children (or invert them first and then assign swapped; both work). Return the node. Equivalent iterative version: BFS with a queue, swapping children of each popped node.
Complexity
Time: O(n). Space: O(h).
Python solution
def invertTree(root):
if root:
root.left, root.right = invertTree(root.right), invertTree(root.left)
return rootJavaScript solution
function invertTree(root) {
if (!root) return null;
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
return root;
}