BFS

LeetCode 429 N-ary Tree Level Order Traversal (Python)

Posted by 小明MaxMing on August 6, 2021

题目

Given an n-ary tree, return the level order traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

解题思路

从根开始按层进行BFS遍历,把每层的数值存到结果里

代码

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root:
            return []
        q = [root]
        res = []
        while q:
            res.append([])
            next_level = []
            for node in q:
                res[-1].append(node.val)
                for child in node.children:
                    next_level.append(child)
            q = next_level
        return res      

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅