# Definition for a Node. classNode: def__init__(self, val=None, children=None): self.val = val self.children = children
classSolution: deflevelOrder(self, root: Optional[Node]) -> List[List[int]]: ans = [] q = [] if root: q.append(root) while q: ans.append([]) for _ inrange(len(q)): thisNode = q[0] q = q[1:] ans[-1].append(thisNode.val) for nextNode in thisNode.children: q.append(nextNode) return ans
针对于Python的语法糖,若使用两个数组可以很大程度上减少代码量(甚至提高效率):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# from typing import Optional, List
# Definition for a Node. classNode: def__init__(self, val=None, children=None): self.val = val self.children = children
classSolution: deflevelOrder(self, root: Optional[Node]) -> List[List[int]]: ans = [] a = [] if root: a.append(root) while a: ans.append([thisNode.val for thisNode in a]) a = [nextChild for thisNode in a for nextChild in thisNode.children] return ans