题目:
给定一个N叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3叉树 :

返回其层序遍历:
[
[1],
[3,2,4],
[5,6]
]
说明:
- 树的深度不会超过
1000。 - 树的节点总数不会超过
5000。
python代码:
"""
# 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):
res,q = [],[root]
while any(q):
res.append([node.val for node in q])
q = [child for node in q for child in node.children if child ]
return res
本文介绍了一种算法,用于解决N叉树的层序遍历问题,通过队列实现,逐步遍历每一层的节点,并返回每层节点值的列表。适用于树的深度不超过1000,节点总数不超过5000的情况。
360

被折叠的 条评论
为什么被折叠?



