题目:

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

 

例如,给定一个 3叉树 :

 

leetcode之N-ary Tree Level Order Traversal(429)

 

返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

 

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 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

 

相关文章:

  • 2022-12-23
  • 2021-08-25
  • 2022-01-18
  • 2022-02-28
  • 2021-09-02
  • 2021-07-26
猜你喜欢
  • 2021-10-19
  • 2021-07-31
  • 2021-08-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2021-12-15
相关资源
相似解决方案