Given the root of a binary tree, invert the tree (mirror it), and return its root.
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Input: root = [2,1,3]
Output: [2,3,1]
Input: root = []
Output: []
Constraints:
- 0 <= Number of nodes <= 100
- -100 <= Node.val <= 100
Contents
- Solution 1 — Recursive DFS
- Solution 2 — Iterative BFS
- Complexity Analysis
Recursive DFS
To invert a tree: swap the left and right children of the current node, then recursively invert each subtree.
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
// Swap left and right children
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// Recursively invert subtrees
invertTree(root.left);
invertTree(root.right);
return root;
}
Iterative BFS
Use a queue to process nodes level by level; swap children at each node.
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
// Swap children
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
return root;
}
- Time: O(n) — every node is visited exactly once.
- Space: O(h) recursive call stack / O(n) BFS queue.