Intuition
Inverting a tree means mirroring it: swap every node's left and right children. Recurse into both subtrees and swap on the way, and the whole tree flips.
Explanation
Idea
Inverting (mirroring) a binary tree just means that at every node, its left and right children trade places. Because this must happen at every node, a simple recursion suffices: invert each subtree, then swap the two children pointers.
Algorithm
- If
rootisNone, returnNone. - Recursively invert the left subtree and the right subtree.
- Swap:
root.left, root.right = inverted_right, inverted_left. - Return
root.
(The order of swapping vs. recursing doesn't matter, as long as both children are swapped.)
Worked example: [4,2,7,1,3,6,9]
4 4
/ \ / \
2 7 -> 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
Every node's children are swapped, producing [4,7,2,9,6,3,1].
Complexity
- Time: O(n) — each node visited once.
- Space: O(h) recursion depth.
Implementation
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}