给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3叉树
:
返回其层序遍历:
[
[1],
[3,2,4],
[5,6]
]
"""
# 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]]
"""
if not root:
return[]
if not root.children:
return [[root.val]]
result=[]
stack=[]
stack.append(root)
while stack:
l=len(stack)
curr=[]
for i in range(l):
node=stack.pop(0)
curr.append(node.val)
for child in node.children:
stack.append(child)
result.append(curr)
return result
执行用时: 160 ms, 在N-ary Tree Level Order Traversal的Python提交中击败了29.38% 的用户
"""
# 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=[root]
result=[]
while any(q):
result.append([node.val for node in q])
q=[child for node in q for child in node.children if child]
return result
#any(x)判断x对象是否为空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true
#all(x)如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False
执行用时: 144 ms, 在N-ary Tree Level Order Traversal的Python提交中击败了99.06% 的用户