Invert Binary Tree
franklinqin0 Tree
# Solution
Let be the number of nodes in the tree.
All following solutions take time and space.
# Brute Force
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
1
2
3
4
5
2
3
4
5
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
1
2
3
4
5
6
7
2
3
4
5
6
7
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return
self.invertTree(root.left)
self.invertTree(root.right)
root.left, root.right = root.right, root.left
return root
1
2
3
4
5
6
7
2
3
4
5
6
7