Given the root of a binary tree, invert the tree, and return its root.
Inverting a binary tree means swapping the left and right children of all nodes in the tree.
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Original Tree: Inverted Tree:
4 4
/ \ / \
2 7 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
Input: root = [2,1,3]
Output: [2,3,1]
Original: Inverted:
2 2
/ \ / \
1 3 3 1
Input: root = []
Output: []
Think about what "invert" means: every node's left child becomes its right child and vice versa.
We can solve this recursively:
The base case is when we reach a null node (leaf's children), where we simply return null.
This is a Tree Traversal + Recursion problem with:
The key insight is that we need to invert every single node in the tree, which naturally fits a recursive pattern.
Why this works:
We can also use a queue (BFS) or stack (DFS):
Time: O(n) where n = number of nodes
Space: O(h) where h = height of tree
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 public TreeNode invertTree(TreeNode root) {
16 // Base case: null node
17 if (root == null) {
18 return null;
19 }
20
21 // Swap left and right children
22 TreeNode temp = root.left;
23 root.left = root.right;
24 root.right = temp;
25
26 // Recursively invert subtrees
27 invertTree(root.left);
28 invertTree(root.right);
29
30 return root;
31 }
32}
33