leetcode429 N叉树层序遍历 -python3

版权声明:转载请声明转自Juanlyjack https://blog.csdn.net/m0_38088359/article/details/82791538

leetcode429 N叉树层序遍历
例如,给定一个 3叉树 :
在这里插入图片描述

返回其层序遍历:

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

说明:

树的深度不会超过 1000。
树的节点总数不会超过 5000。

其中leetcode的输入为:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …,"children":[{"id”:“2”,“children”:[{“KaTeX parse error: Expected 'EOF', got '}' at position 30: …ren":[],"val":5}̲,{"id”:“6”,“children”:[],“val”:6}],“val”:3},{“KaTeX parse error: Expected 'EOF', got '}' at position 30: …ren":[],"val":2}̲,{"id”:“4”,“children”:[],“val”:4}],“val”:1}

"""
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def levelOrder(self, root):
        queue = []
        r = []
        queue.append(root)
        while len(queue)>0:
            layer = []
            length = len(queue)
            for l in range(length):
                current = queue.pop(0)
                layer.append(current.val)
                for child in current.children:
                    queue.append(child)
            r.append(layer)
        return r

猜你喜欢

转载自blog.csdn.net/m0_38088359/article/details/82791538