-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path0226-Invert-Binary-Tree.py
More file actions
44 lines (39 loc) · 972 Bytes
/
0226-Invert-Binary-Tree.py
File metadata and controls
44 lines (39 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'''
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
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.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
queue = []
queue.append(root)
while queue:
cur = queue.pop(0)
cur.left, cur.right = cur.right, cur.left
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return root