Skip to Content

Invert a Binary Tree

Home | Coding Interviews | Simple Data Structures | Invert a Binary Tree

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

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root: #Base Case
            return root
        self.invertTree(root.left) #Call the left substree
        self.invertTree(root.right)  #Call the right substree
        # Swap the nodes
        root.left, root.right = root.right, root.left
        return root # Return the root

Posted by Jamie Meyer a month ago