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叉树,让我们对其进行层序遍历。我们做过之前二叉树的层序遍历的那道题的话Binary Tree Level Order Traversal,那么这道题也就不难了。虽说现在每一个结点可能有很多个子结点,但其实处理的思路的都是一样的。子结点放到了一个children数组中,我们访问的时候只要遍历数组就行了。先来看迭代的写法,用到了队列queue来辅助,首先判断root是否为空,为空直接返回空数组,否则加入queue中。然后遍历queue,这里用的trick就是,要加个for循环,要将当前queue中的结点的个数统计下来,因为再加入下一层的结点时,queue的结点个数会增加,而在加入下一层结点之前,当前queue中的结点个数全都属于一层,所以我们要把层与层区分开来,将同一层的结点都放到一个数组out中,之后再放入结果res中,这种层序遍历的思想在迷宫遍历找最短路径的时候应用的也很多,是个必须要掌握的方法呢,参见代码如下:

解法一:

class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if (!root) return {};
vector<vector<int>> res;
queue<Node*> q{{root}};
while (!q.empty()) {
vector<int> out;
for (int i = q.size(); i > ; --i) {
auto t = q.front(); q.pop();
out.push_back(t->val);
if (!t->children.empty()) {
for (auto a : t->children) q.push(a);
}
}
res.push_back(out);
}
return res;
}
};

下面再来看递归的写法,其实层序遍历天然适合迭代的写法,但我们强行递归也是可以的,就是有点秀。由于递归DFS的设定是一条路走到黑再返回,那么必然会跨越不同的层数,所以为了区别当前的层,我们需要一个变量level来标记当前的层数,根结点root就是第0层,依此类推往上加。然后还有个trick就是关于结果res的大小,由于我们并不知道树的深度,所以一旦我们遍历的层数超过了当前res的大小,我们需要resize一下,这样才不会出错。之后,我们将当前遍历到的结点加到res中的第level层中,然后遍历子结点数组,对每一个子结点调用递归函数即可,参见代码如下:

解法二:

class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> res;
helper(root, , res);
return res;
}
void helper(Node* node, int level, vector<vector<int>>& res) {
if (!node) return;
if (res.size() <= level) res.resize(res.size() + );
res[level].push_back(node->val);
for (auto a : node->children) {
helper(a, level + , res);
}
}
};

类似题目:

Binary Tree Level Order Traversal

N-ary Tree Preorder Traversal

N-ary Tree Postorder Traversal

参考资料:

https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/

https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/156218/Typical-C++-recursive-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] N-ary Tree Level Order Traversal N叉树层序遍历的更多相关文章

  1. [LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

  2. leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)

    题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...

  3. [LeetCode] Binary Tree Level Order Traversal II 二叉树层序遍历之二

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

  4. 【LeetCode】102. Binary Tree Level Order Traversal 二叉树的层序遍历 (Python&C++)

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

  5. LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历 C++

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  6. Binary Tree Level Order Traversal II(层序遍历2)

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

  7. leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历

    基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行 ...

  8. 【LeetCode】Binary Tree Level Order Traversal(二叉树的层次遍历)

    这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15 ...

  9. Java for LeetCode 107 Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

随机推荐

  1. 第六节:深入研究Task实例方法ContinueWith的参数TaskContinuationOptions

    一. 整体说明 揭秘: 该章节的性质和上一个章节类似,也是一个扩展的章节,主要来研究Task类下的实例方法ContinueWith中的参数TaskContinuationOptions. 通过F12查 ...

  2. python下调用pytesseract识别某网站验证码

    一.pytesseract介绍 1.pytesseract说明 pytesseract最新版本0.1.6,网址:https://pypi.python.org/pypi/pytesseract Pyt ...

  3. UE导航系统详

    配置 Navigation Crowd Manager Class 代理人管理类 可以自定义个 Navigation System Auto Create Navigation Data 导航数据在没 ...

  4. http协议——无连接、无状态

    无连接 无连接的含义是限制每次连接只处理一个请求.服务器处理完客户的请求,并收到客户的应答后,即断开连接.采用这种方式可以节省传输时间. 早期这么做的原因是 HTTP 协议产生于互联网,因此服务器需要 ...

  5. 【原创】Java基础之ClassLoader类加载器简介

    classloader简介 1 classloader层次结构(父子关系) Bootstrap(ClassLoader) ExtClassLoader AppClassLoader XXXClassL ...

  6. 使用virtualenvwrapper模块管理python虚拟环境

    1.pip安装virtualenvwrapper [root@localhost ~]# pip install virtualenvwrapper # 安装virtualenvwrapper [ro ...

  7. Connet Scanning

    1.connect scanning with Scapy,   Tools that perform  Tcp scans operate by performing a full there-wa ...

  8. Mongodb字段自增长

    MongoClient client = new MongoClient("mongodb://xxx.xxx.x.xx:27017"); var mongServer = cli ...

  9. android studio——替换全局的某个字符串

    android studio——替换全局的某个字符串 edit - > replace in path https://blog.csdn.net/dragon0103/article/deta ...

  10. 【转】GB2312、GBK和UTF-8三种编码的简要说明

    原文地址:http://www.cnblogs.com/hust-yingjie/p/5481966.htmlGB2312.GBK和UTF-8都是一种字符编码,除此之外,还有好多字符编码.只是对于我们 ...