【Leetcode】每日一题:N 叉树的层序遍历

编程入门 行业动态 更新时间:2024-10-10 00:26:47

【Leetcode】每日一题:N 叉树的层序<a href=https://www.elefans.com/category/jswz/34/1771029.html style=遍历"/>

【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 叉树的层序遍历

本文发布于:2024-03-12 06:56:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1730945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   Leetcode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!