一、题目描述
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
例如,给定一个 3叉树 :
二、代码实现
"""
# 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 root == None: return []
queue = [root]
res = []
while queue:
layer = []
for i in range(len(queue)):
ele = queue.pop(0)
layer.append(ele.val)
if not ele.children: continue
for child in ele.children: queue.append(child)
res.append(layer)
return res
网友评论