-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path102.py
70 lines (59 loc) · 2.04 KB
/
102.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
__________________________________________________________________________________________________
sample 24 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
levels = []
lvl = 0
from collections import deque
q = deque([root,])
while q:
levels.append([])
lvlLen = len(q)
for _ in range(lvlLen):
node = q.popleft()
levels[lvl].append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
lvl += 1
return levels
__________________________________________________________________________________________________
sample 13144 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
return self.bfs(root)
# bfs, time: O(n), space: O(n)
def bfs(self,root):
res = []
cur, nex = [], [] # cur stores current level nodes, nex stores next level nodes
cur.append(root)
i = 0
while cur != []:
res.append([])
for node in cur:
res[i].append(node.val)
if node.left:
nex.append(node.left)
if node.right:
nex.append(node.right)
cur, nex = nex, []
i += 1
return res
__________________________________________________________________________________________________