Problem Statement
Given the root of a binary tree, invert the tree, and return its root. Inverting means swapping the left and right subtrees at every node.
Intuition
Inverting a binary tree is a classic recursive problem. At each node, we swap the left and right children, then recursively invert each subtree.
Approach
- If the node is null, return null (base case).
- Swap the left and right children.
- Recursively invert the left and right subtrees.
- Return the node.
Solution
TypeScript
function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) return null;
const temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Visit each node exactly once | |
| Space | Recursive call stack, where h is tree height |