Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary
tree:
结果为
[
[1],
[3,2,4],
[5,6]
]
解法:
BFS,广度优先搜索
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
q, res = [root], []
while any(q):
v = []
res.append([node.val for node in q])
for node in q:
for child in node.children:
if child:
v.append(child)
q = v
return res```
网友评论