题目地址:https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/

题目描述

Given an n-ary tree, return the postorder traversal of its nodes’ values.

For example, given a 3-ary tree:

Return its postorder traversal as: [5,6,3,2,4,1].

Note: Recursive solution is trivial, could you do it iteratively?

题目大意

N叉树的后序遍历。

解题方法

递归

首先得明白,这个N叉树是什么样的数据结构定义的。val是节点的值,children是一个列表,这个列表保存了其所有节点。

后序遍历,如果通过递归还是非常简单的。对其子节点遍历,在对其本身节点遍历即可。由于所有的子节点是个列表,这样甚至比二叉树还要简单,只需对列表进行循环就行了。

Python代码如下:

"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res = []
if not root:
return res
for child in root.children:
res.extend(self.postorder(child))
res.append(root.val)
return res

C++代码如下:

/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> res;
if (!root) return res;
for (Node* child : root->children) {
vector<int> child_vector = postorder(child);
res.insert(res.end(), child_vector.begin(), child_vector.end());
}
res.push_back(root->val);
return res;
}
};

迭代

这个题希望我们使用迭代方法去做,即使用迭代的方法得到后序遍历。由于后序遍历把根节点放到了最后,而我们在遍历的过程中,一定先获得到根节点,那么我们可以先倒序,然后再反转。

后序遍历:左->右->根
我们的做法:根->右->左,然后再反转。

即,先把根节点放入栈中,然后把它的孩子从左到右依次放入,这样我们下次对栈内的元素遍历得到的顺序就是从右向左的,对于栈中弹出的每个节点都是如此。

得到的顺序是根->右子树(节点全部入栈)->左子树的遍历方式,最后需要加一个翻转即可得到想要的后序遍历。

Python代码如下:

"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res = []
if not root:
return res
stack = [root,]
while stack:
node = stack.pop()
stack.extend(node.children)
res.append(node.val)
return res[::-1]

C++代码如下:

/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> res;
if (!root) return res;
stack<Node*> st;
st.push(root);
while (!st.empty()) {
Node* node = st.top(); st.pop();
if (!node) continue;
for (Node* child : node->children) {
st.push(child);
}
res.push_back(node->val);
}
reverse(res.begin(), res.end());
return res;
}
};

相似题目

https://blog.csdn.net/fuxuemingzhu/article/details/81021950

参考资料

https://leetcode.com/articles/n-ary-tree-postorder-transversal/

日期

2018 年 7 月 12 日 —— 天阴阴地潮潮,已经连着两天这样了
2018 年 11 月 5 日 —— 打了羽毛球,有点累

【LeetCode】590. N-ary Tree Postorder Traversal 解题报告 (C++&Python)的更多相关文章

  1. 【LeetCode】145. Binary Tree Postorder Traversal 解题报告 (C++&Python)

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

  2. 【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)

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

  3. LeetCode: Binary Tree Postorder Traversal 解题报告

    Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' va ...

  4. LeetCode 590 N-ary Tree Postorder Traversal 解题报告

    题目要求 Given an n-ary tree, return the postorder traversal of its nodes' values. 题目分析及思路 题目给出一棵N叉树,要求返 ...

  5. 【LeetCode】889. Construct Binary Tree from Preorder and Postorder Traversal 解题报告(Python & C++)

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

  6. 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...

  7. 【LeetCode】589. N-ary Tree Preorder Traversal 解题报告 (Python&C++)

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

  8. 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告

    [LeetCode]106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告(Python) 标签: LeetCode ...

  9. 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)

    [LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...

随机推荐

  1. Scrapy-Splash的安装和使用

    Scrapy-Splash是一个Scrapy中支持JavaScript渲染的工具. Scrapy-Splash的安装分为两部分.一个是Splash服务的安装,具体是通过Docker,安装之后,会启动一 ...

  2. C#生成编号

    //自动生成账单编号 public string GetNewPoID(string Prefix) { string NewPoID = Prefix + DateTime.Now.Year.ToS ...

  3. C#时间选择

    <script type="text/javascript" src="http://www.shicishu.com/down/WdatePicker.js&qu ...

  4. 学习java 7.18

    学习内容: Lambda表达式的格式:(形式参数)  ->  {代码块} 如果有多个参数,参数之间用逗号隔开 new Thread(  ()   ->   { System.out.pri ...

  5. acid, acknowledge, acquaint

    acid sulphuric|hydrochloric|nitric|carbolic|citric|lactic|nucleic|amino acid: 硫|盐|硝|碳|柠檬|乳|核|氨基酸 王水是 ...

  6. Ubuntu Linux安装QT5之旅

    1. QT 版本选择 如何选择QT版本,参考如下介绍 https://www.cnblogs.com/chinasoft/p/15226293.html 2.  在此以5.15.0解说 下载QT 版本 ...

  7. Scala(七)【异常处理】

    目录 一.try-catch-finally 二.Try(表达式).getOrElse(异常出现返回的默认值) 三. 直接抛出异常 一.try-catch-finally 使用场景:在获取外部链接的时 ...

  8. 轻松理解webpack热更新原理

    一.前言 - webpack热更新 Hot Module Replacement,简称HMR,无需完全刷新整个页面的同时,更新模块.HMR的好处,在日常开发工作中体会颇深:节省宝贵的开发时间.提升开发 ...

  9. Linux基础命令---uptime

    uptime uptime指令用来显示系统运行多长时间.有多少用户登录.系统负载情况. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.SUSE.openSUSE. ...

  10. vue-cli 如何配置assetsPublicPath; vue.config.js如何更改assetsPublicPath配置;

    问题: vue项目完成打包上线的时候遇到静态资源找不到的问题,网上很多解决办法都是基于vue-cli 2.x 来解决的,但从vue-cli 3.0以后,便舍弃了配置文件夹(便没有了config这个文件 ...