【LeetCode】429. N-ary Tree Level Order Traversal 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/
题目描述
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.
题目大意
N叉树的层次遍历。
解题方法
方法一:BFS
首先得明白,这个N叉树是什么样的数据结构定义的。val是节点的值,children是一个列表,这个列表保存了其所有节点。
层次遍历比较好理解,就是每层的值保存在一个list中,总的再返回一个list即可。
我们知道这个属于先进先出的结构,其实就是用队列就好了。需要注意是每层都在一个list中,所以在进入队列的时候需要保存一下这个节点属于哪个层。这样当遍历它的时候,就能直接放入它那层的list的末尾即可。难点在维护这个层数。
另外犯了一个小错,当root不存在的时候应该返回的是[],而不是[[]]。
代码如下:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
queue = [(root, 0)]
res = [[]]
while queue:
node, level = queue.pop(0)
if level >= len(res):
res.append([])
res[level].append(node.val)
for child in node.children:
queue.append((child, level + 1))
return res
二刷,换了一个BFS的写法,我认为下面的这个写法更清晰,而且是个模板,可以直接交套用。
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
res = []
que = collections.deque()
que.append(root)
while que:
level = []
size = len(que)
for _ in range(size):
node = que.popleft()
if not node:
continue
level.append(node.val)
for child in node.children:
que.append(child)
if level:
res.append(level)
return res
方法二:DFS
实现起来稍微难了一点,因为需要我们根据层数来添加到对应的数组里面去。不过这个比一般的递归简单的地方在于不用考虑root节点的值在什么位置进行添加,因为不在同一层,不会相互影响的。
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
res = []
self.getLevel(root, res, 0)
return res
def getLevel(self, root, res, level):
if not root:
return []
if level == len(res):
res.append([])
res[level].append(root.val)
for child in root.children:
self.getLevel(child, res, level + 1)
return res
参考资料
637. Average of Levels in Binary Tree
日期
2018 年 7 月 12 日 —— 天阴阴地潮潮,已经连着两天这样了
2018 年 11 月 9 日 —— 睡眠可以
【LeetCode】429. N-ary Tree Level Order Traversal 解题报告(Python)的更多相关文章
- 【LeetCode】102. Binary Tree Level Order Traversal 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目描述 Given a bi ...
- LeetCode: Binary Tree Level Order Traversal 解题报告
Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...
- LeetCode 429 N-ary Tree Level Order Traversal 解题报告
题目要求 Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to r ...
- 【一天一道LeetCode】#107. Binary Tree Level Order Traversal II
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...
- 【LeetCode】107. Binary Tree Level Order Traversal II (2 solutions)
Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order traversal ...
- 【LeetCode】102. Binary Tree Level Order Traversal (2 solutions)
Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...
- 【一天一道LeetCode】#102. Binary Tree Level Order Traversal
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...
- 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告
Binary Tree Zigzag Level Order Traversal [LeetCode] https://leetcode.com/problems/binary-tree-zigzag ...
- 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...
随机推荐
- linux下vi与vim区别以及vim的使用-------vim编辑时脚本高光显示语法
vi与vimvi编辑器是所有Unix及Linux系统下标准的编辑器,他就相当于windows系统中的记事本一样,它的强大不逊色于任何最新的文本编辑器.他是我们使用Linux系统不能缺少的工具.由于对U ...
- KEPServeEX 6与KepOPC中间件测试
KEPServeEX 6可以组态服务器端和客户端连接很多PLC以及具有OPC服务器的设备,以下使用KEPServeEX 6建立一个OPC UA服务器,然后使用KepOPC建立客户端来连接服务器做测试. ...
- 关于写SpringBoot+Mybatisplus+Shiro项目的经验分享一:简单介绍
这次我尝试写一个原创的项目 the_game 框架选择: SpringBoot+Mybatisplus+Shiro 首先是简单的介绍(素材灵感来自英雄联盟) 5个关键的表: admin(管理员): l ...
- JAVA中数组的基本概念与用法
JAVA中数组的基本概念与用法 1. 数组的定义与特点 数组的一种引用数据类型 数组中可以同时存放多个数据,但是数据的类型必须统一 数组的长度在开始时就需要确定,在程序运行期间是不可改变的 虽然可以使 ...
- Java、Scala类型检查和类型转换
目录 Java 1.类型检查 2.类型转换 Scala 1.类型检查 2.类型转换 Java 1.类型检查 使用:变量 instanceof 类型 示例 String name = "zha ...
- 【STM32】使用SDIO进行SD卡读写,包含文件管理FatFs(三)-SD卡的操作流程
其他链接 [STM32]使用SDIO进行SD卡读写,包含文件管理FatFs(一)-初步认识SD卡 [STM32]使用SDIO进行SD卡读写,包含文件管理FatFs(二)-了解SD总线,命令的相关介绍 ...
- Linux基础命令---ab测试apache性能
ab ab指令是apache的性能测试工具,它可以测试当前apache服务器的运行性能,显示每秒中可以处理多少个http请求. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.F ...
- Linux基础命令---htpasswd创建密码文件
htpasswd htpasswd指令用来创建和更新用于基本认证的用户认证密码文件.htpasswd指令必须对密码文件有读写权限,否则会返回错误码. 此命令的适用范围:RedHat.RHEL.Ubun ...
- my37_MGR流控对数据库性能的影响以及MGR与主从的性能对比
mysql> show variables like 'group_replication_flow_control_applier_threshold'; +----------------- ...
- vscode高效管理不同项目文件
vscode作为一个轻量级编辑器,深受大家喜爱,这其中当然也囊括了本人.我同时使用vscode写c++.java.python以及markdown文档,每次打开vscode都要切换到对应的文件夹,非常 ...