# 590. N-ary Tree Postorder Traversal N 叉树的后序遍历

@TOC

## # 题目描述

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叉树的后序遍历。

## # 解题方法

### # 递归

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 日 —— 打了羽毛球，有点累