[LeetCode] Challenge log 226

226. Invert Binary Tree

DFS will do.


Invert a binary tree.

1
2
3
4
5
     4
/ \
2 7
/ \ / \
1 3 6 9

to

1
2
3
4
5
     4
/ \
7 2
/ \ / \
9 6 3 1

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.


Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None: return None
tmp1 = self.invertTree(root.left)
tmp2 = self.invertTree(root.right)
root.left = tmp2
root.right = tmp1
return root
0%