-
Notifications
You must be signed in to change notification settings - Fork 0
/
429. Sequence traversal of N-forked trees
44 lines (42 loc) · 1.17 KB
/
429. Sequence traversal of N-forked trees
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
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# 建立两个队列:currLayer和nextLayer
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
# if root == None:
# return []
# currLayer = [root]
# res = []
# while True:
# currVals = []
# nextLayer = []
# while len(currLayer) > 0:
# currNode = currLayer.pop(0)
# currVals.append(currNode.val)
# for i in currNode.children:
# nextLayer.append(i)
# res.append(currVals)
# if len(nextLayer) == 0:
# return res
# currLayer = nextLayer
if not root:
return []
res=[]
stack=[root]
while stack:
res.append([node.val for node in stack])
temp=[]
for node in stack:
for n in node.children:
temp.append(n)
stack=temp
return res