Faaez Razeen

Invert Binary Tree

  • 1 min read
  • DFS
  • BFS
  • Tree
  • LC-Easy
  • Blind75
  • Binary Tree

3 years ago

Approach 1: Recursion

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

Approach 2: Iterative

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