Problem Description
Given the root of a binary tree, invert the tree by swapping the left and right subtrees recursively, and return the root of the inverted tree.
Key Insights
- The problem can be solved using recursion (depth-first search) by swapping the children of every node.
- Alternatively, an iterative approach (using a queue for breadth-first search) can be used.
- The recursion terminates when a null node is encountered.
- The operation is performed in-place, modifying the original tree structure.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes, since each node is visited once. Space Complexity: O(h) where h is the height of the tree, which is the recursion stack space in the recursive approach. In worst-case (skewed tree), this could be O(n).
Solution
We solve the problem using recursion (depth-first search). The approach is to:
- Check the base case: if the node is null, simply return null.
- Recursively invert the left subtree and the right subtree.
- Swap the left and right children of the current node.
- Return the current node after the swap. The recursive approach elegantly handles all nodes and ensures the inversion process covers the complete tree.