问题描述:
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:
We should return its level order traversal:
[ [1], [3,2,4], [5,6] ]
Note:
- The depth of the tree is at most
1000
. - The total number of nodes is at most
5000
.
思路:此题是在leetcode上见到的第一个BFS的题目,因而记录。同时注意该句代码应用方式 Node,level = queue.pop()
代码:
1 """ 2 # Definition for a Node. 3 class Node: 4 def __init__(self, val, children): 5 self.val = val 6 self.children = children 7 """ 8 class Solution: 9 def levelOrder(self, root: 'Node') -> List[List[int]]: 10 if not root: 11 return [] 12 13 result, queue = [],[(root,1)] 14 while queue: 15 Node,level = queue.pop() 16 if level - len(result) >= 1: 17 result.append([]) 18 result[level - 1].append(Node.val) 19 20 for child in Node.children: 21 queue.insert(0,(child,level+ 1)) 22 return result