Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 1000 Bytes

File metadata and controls

38 lines (31 loc) · 1000 Bytes

226. Invert Binary Tree

Solution 1

class Solution:
    def invertTree(self, root):
        if root:
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
            return root

{% hint style="info" %} This is a simple recursive method. {% endhint %}

Solution 2

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

{% hint style="info" %} Simple iterative method using stack. {% endhint %}