-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path429.py
77 lines (67 loc) · 2.11 KB
/
429.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
71
72
73
74
75
76
77
__________________________________________________________________________________________________
sample 628 ms submission
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
from collections import deque
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None:
return []
res = []
q = deque([root])
while q:
lenq = len(q)
level = []
for _ in range(lenq):
node = q.popleft()
level.append(node.val)
if len(node.children) > 0:
q += node.children
res.append(level[:])
return res
__________________________________________________________________________________________________
sample 17468 kb submission
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
# if not root:
# return []
# q = collections.deque()
# q.append(root)
# retlist = []
# while q:
# q_len = len(q)
# levellist = []
# for i in range(q_len):
# node = q.popleft()
# levellist.append(node.val)
# for child in node.children:
# q.append(child)
# retlist.append(levellist)
# return retlist
if not root:
return []
res = []
stack = [root]
while stack:
temp = []
next_stack = []
for node in stack:
temp.append(node.val)
for child in node.children:
next_stack.append(child)
stack = next_stack
res.append(temp)
return res
__________________________________________________________________________________________________