美文网首页
429. N-ary Tree Level Order Trav

429. N-ary Tree Level Order Trav

作者: 腹黑君 | 来源:发表于2020-05-27 11:37 被阅读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```

    相关文章

      网友评论

          本文标题:429. N-ary Tree Level Order Trav

          本文链接:https://www.haomeiwen.com/subject/gnpaaftx.html