0226. Invert Binary Tree

Easy | Tree + Recursion / Stack | 16 ms (99.96%), 14 MB (90.10%)

Source: LeetCode - Invery Binary Tree GitHub: Solution / Performance

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

Swap left- and right-pointer in each iteration.

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        # (base case)
        if (not root) or (not root.left and not root.right): return root
        
        # ==================================================
        #  Binary Tree                       (Iterative)   =
        # ==================================================
        # time  : O(n)
        # space : O(n)
        
        stack = [root]
        while stack:
            node = stack.pop()
                
            node.left, node.right = node.right, node.left
            if node.left: stack.append(node.left)
            if node.right: stack.append(node.right)
            
        return root
            
        '''
        # ==================================================
        #  Tree                              (Recursive)   =
        # ==================================================
        # time  : O(n)
        # space : O(n)
        
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        
        return root
        '''

Last updated