作者: 负雪明烛
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:

  1. The depth of the tree is at most 1000.
  2. 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)的更多相关文章

  1. 【LeetCode】102. Binary Tree Level Order Traversal 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目描述 Given a bi ...

  2. LeetCode: Binary Tree Level Order Traversal 解题报告

    Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...

  3. 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 ...

  4. 【一天一道LeetCode】#107. Binary Tree Level Order Traversal II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...

  5. 【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 ...

  6. 【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 ...

  7. 【一天一道LeetCode】#102. Binary Tree Level Order Traversal

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...

  8. 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告

    Binary Tree Zigzag Level Order Traversal [LeetCode] https://leetcode.com/problems/binary-tree-zigzag ...

  9. 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...

随机推荐

  1. 7本Python必读的入门书籍,你看过吗?(附福利)

    Python入门书籍不用看太多,看一本就够.重要的是你要学习Python的哪个方向,或者说你对什么方向感兴趣,因为Python这门语言的应用领域比较广泛,比如说可以用来做数据分析.机器学习,也可以用来 ...

  2. Swift-技巧(十) Protocol 的灵活使用

    摘要 Protocol 是 Swift 中实现面向协议编程思想的重要部分.在使用过程中有遇到协议中声明的部分,但是在遵守部分不需要实现的,那么就需要使用 extension 参与进来,让 Protoc ...

  3. 初学者如何吃透一个Java项目

    不少初学者朋友在学习Java过程中,会对着视频敲Java项目,其中遇到的BUG还能解决,但就是每次敲完一个项目,就感觉很空虚,项目里面的知识点感觉懂了但又好像没懂 这些朋友应该怎样才能掌握一个项目所用 ...

  4. typedef定义数组

    typedef定义数组 问题来源 在学习高一凡数据结构与算法解析串这一章节时,遇到如下代码不明白其意义,经过查阅终于搞明白 typedef unsigned char SString[MAXLEN + ...

  5. 学习java 6.30

    学习内容:Java的运算符与C中类似,虽是类似,还是有点区别,在这里详细说明一下,即字符以及字符串的+操作,字符的+操作执行后需要赋值给表达式中数据范围最大的类型, 字符串的+操作,当+中有字符串,则 ...

  6. Java中特殊的类——包装类

    Java中特殊的类--包装类 包装类就是将基本数据类型封装在类中. 1.包装类 (1)自定义包装类 将基本数据类型包装成一个类对象的本质就是使用Object进行接收处理. 此时IntDemo类就是in ...

  7. Oracle中分割逗号函数REGEXP_SUBSTR

    最近优化FORM中的查询条件遇到某个字段可以选取多个值的问题,思路当然就是选取时将多个值通过某个符号拼接起来,查询数据的时候将拼接后的字符串按照符号分割开,在分割逗号的时候用到了一个新的方法REGEX ...

  8. Java线程安全性-原子性工具对比

    synchronized 不可中断锁,适合竞争不激烈的场景,可读性好,竞争激烈时性能下降很快 Lock 可中断锁,多样化同步,竞争激烈时能维持常态 Atomic 竞争激烈时能维持常态,比Lock性能还 ...

  9. 【C/C++】拔河比赛/分组/招商银行

    题目:小Z组织训练营同学进行一次拔河比赛,要从n(2≤n≤60,000)个同学中选出两组同学参加(两组人数可能不同).对每组同学而言,如果人数超过1人,那么要求该组内的任意两个同学的体重之差的绝对值不 ...

  10. 【C/C++】日期问题/算法笔记/入门模拟

    最近把算法竞赛入门经典的前半部分看完了,开始看算法笔记入门算法. 看了前半部分的例题,很多是算法竞赛入门经典中出现过的,但是感觉这本书写的更适合初学者,而且真的很像考试笔记,通俗易懂. //日期问题 ...