The solution is short, but very recursive. As it happens, this can be accomplished without changing the root node pointer, so the return-the-new-root construct is not necessary. Alternately, if you do not want to change the tree nodes, you may construct and return a new mirror tree based on the original tree.
Method 1 - Recursion without Separate Helper Function#
classSolution:
definvertTree(self, root: Optional['TreeNode']) -> Optional['TreeNode']:
if root isNone:
returnNone# Swap the left and right children root.left, root.right = root.right, root.left
# Recursively invert the left and right subtrees self.invertTree(root.left)
self.invertTree(root.right)
return root
⏰ Time complexity: O(n) where n is the number of nodes in the tree. Each node is visited once.
🧺 Space complexity: O(h) where h is the height of the tree. In the worst case of a skewed tree, the recursion stack will go up to the height of the tree, which is O(n) in the worst case.