Optimal Recursive / Depth-First Search Approach:
- Recursively swap the left and right child pointers for every node in the binary tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree(root: TreeNode) -> TreeNode:
if not root:
return None
# Swap left and right children
root.left, root.right = root.right, root.left
# Recurse down subtrees
invert_tree(root.left)
invert_tree(root.right)
return root
Complexity & Key Logic:
- Time Complexity: O(N) visiting each of the N nodes exactly once.
- Space Complexity: O(H) call stack space, where H is tree height (O(log N) for balanced trees, O(N) for degenerate trees).
- Algorithm Details:
- Base Case: If node is None, return None.
- Swap current node's left and right pointers.
- Recursively invert the newly swapped subtrees.
- Return original root node.