We can use a recursive approach. For each node, we swap its left and right children and then recursively call the function for both.
- If
rootis None, return None. - Swap
root.leftandroot.right. - Recursively call
invert_tree(root.left). - Recursively call
invert_tree(root.right). - Return
root.
- Time Complexity: O(N).
- Space Complexity: O(H).
def invert_tree(root):
if not root:
return None
# Swap children
root.left, root.right = root.right, root.left
# Recurse
invert_tree(root.left)
invert_tree(root.right)
return root