429. N-ary Tree Level Order Trav

2020-05-27  本文已影响0人  腹黑君

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:

image

结果为

[
     [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```
上一篇下一篇

猜你喜欢

热点阅读