SDE & MLE Prep

226. Invert Binary Tree

Problem

Mirror a binary tree, swapping the left and right child of every node, and return its root. (Trees are written in level order, with null for a missing child.)

Example: [4,2,7,1,3,6,9] → [4,7,2,9,6,3,1]

Swap the children of every node (any traversal order works).

     4              4
   2   7    ->    7   2
  1 3 6 9        9 6 3 1

Complexity: O(n) time, O(h) stack.

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