- Easy
- Given the
root
of a binary tree, invert the tree, and return its root. - https://leetcode.com/problems/invert-binary-tree/
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 %}
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 %}