Problem
Given the root
of a binary tree, invert the tree, and return its root.
Example 1:
Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
Intuition
The problem requires inverting a binary tree, which means swapping the left and right subtrees for each node. This operation essentially reflects the binary tree across its vertical axis. The goal is to transform the given tree into its mirror image.
Approach
Base Case: Check if the root is None (empty tree). If so, return None.
Swap Left and Right Subtrees: Swap the left and right subtrees of the current root node.
Recursion: Recursively apply the same inversion process to the left and right subtrees.
Return Root: Return the root of the modified tree.
Complexity
- Time complexity:
The time complexity of this solution is O(n), where n is the number of nodes in the binary tree. The function visits each node exactly once, and the inversion operation (swapping left and right subtrees) takes constant time.
- Space complexity:
The space complexity is O(h), where h is the height of the binary tree. In the worst case, the function call stack will have a maximum depth equal to the height of the tree. This is because the recursion is depth-first, and the space required on the call stack is proportional to the height of the tree. In the average case, for a balanced binary tree, the height is O(log n), making the space complexity O(log n). However, in the worst case of an unbalanced tree, the height could be O(n), resulting in a space complexity of O(n).
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
temp = root.left
root.left = root.right
root.right = temp
self.invertTree(root.left)
self.invertTree(root.right)
return root