Home Leetcode

Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Constraints:

As with all tree questions, we can use recursion to complete this question.

def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
    if root is None:
        return root
    
    root.left, root.right = root.right, root.left
    self.invertTree(root.left)
    self.invertTree(root.right)

    return root

Time Complexity

Since every node must be inverted and each recursive call is constant time, we have O(n)\mathcal{O}(n) time complexity.

Space Complexity

Since we don’t use any extra variables other than the input tree, we have constant space complexity.