Problem
Given the root of a binary tree, invert the tree and return its root. Inverting a binary tree means swapping the left and right child of every node.Example(s)
Consider the following example(s) to understand the expected input and output.Input
root = [4,2,7,1,3,6,9]
4
/ \
2 7
/ \ / \
1 3 6 9
Output
root = [4,7,2,9,6,3,1]
4
/ \
7 2
/ \ / \
9 6 3 1
Solution
This solution uses Depth-First Search (DFS) with recursion. For each node, its left and right children are swapped.The same process is then applied recursively to both subtrees. When a
null node is reached, the recursion stops.
After all nodes have been processed, the entire binary tree is inverted.
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
// Recursively invert both subtrees
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
// Swap left and right subtrees
root.left = right;
root.right = left;
return root;
}
}
Complexity
Each node in the binary tree is visited exactly once, resulting in a time complexity ofO(n).
The recursive call stack can grow up to the height of the tree, resulting in an extra space complexity of
O(h), where h is the height of the tree.