LeetCode 429 N-ary Tree Level Order Traversal 解题报告

时间:2021-06-18 05:04:53

题目要求

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

题目分析及思路

给定一棵N叉树,要求返回它的层次遍历结果。可以使用collections.deque来保存结点,按照每一层的长度来遍历结点。

python代码

"""

# Definition for a Node.

class Node:

def __init__(self, val, children):

self.val = val

self.children = children

"""

class Solution:

def levelOrder(self, root: 'Node') -> List[List[int]]:

order1 = []

q = collections.deque()

q.append(root)

while q:

order2 = []

size = len(q)

for _ in range(size):

node = q.popleft()

if not node:

continue

order2.append(node.val)

for child in node.children:

q.append(child)

if order2:

order1.append(order2)

return order1