遍历"/>
【Leetcode】每日一题:N 叉树的层序遍历
N 叉树的层序遍历
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)
AC代码
"""
# Definition for a Node.
class Node:def __init__(self, val=None, children=None):self.val = valself.children = children
"""class Solution:def levelOrder(self, root: 'Node') -> List[List[int]]:if root is None:return []result = []queue = [root]while queue != []:temp = []t = copy.deepcopy(queue)for r in t:temp.append(r.val)queue.pop(0)queue += r.childrenresult.append(temp)return result
官方代码
class Solution:def levelOrder(self, root: 'Node') -> List[List[int]]:if not root:return []ans = list()q = deque([root])while q:cnt = len(q)level = list()for _ in range(cnt):cur = q.popleft()level.append(cur.val)for child in cur.children:q.append(child)ans.append(level)return ans# 作者:LeetCode-Solution
1、官方代码用的双端队列,本质其实和笔者的代码是相同的
更多推荐
【Leetcode】每日一题:N 叉树的层序遍历
发布评论