解法
同二叉树相似,有迭代法和递归法两种
递归法
作者:macRong
链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/solution/cshi-xian-ncha-shu-de-hou-xu-bian-li-by-macrong-2/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
// 后序遍历,首先最简单的做法是 记住前序 翻转就实现 (直接利用 1.前序遍历 2.翻转)
// 后插入
// 第一种:递归
vector<int> postorder(Node* root) {
vector<int> ve;
if (!root) return ve;
recursivePreorder(root, ve);
return ve;
}
void recursivePreorder(Node *node, vector<int>& ve) {
if (!node) return;
for (int i=0; i < node->children.size(); i ++) {
Node *n = node->children[i];
if (n) recursivePreorder(n,ve);
}
ve.emplace_back(node->val);
}
};
迭代法
复杂度分析
时间复杂度:时间复杂度:O(M),其中 M 是 N 叉树中的节点个数。每个节点只会入栈和出栈各一次。
空间复杂度:O(M)。在最坏的情况下,这棵 N 叉树只有 2 层,所有第 2 层的节点都是根节点的孩子。将根节点推出栈后,需要将这些节点都放入栈,共有 M - 1M−1 个节点,因此栈的大小为 O(M)。
作者:macRong
链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/solution/cshi-xian-ncha-shu-de-hou-xu-bian-li-by-macrong-2/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> ve;
if (!root) return ve;
stack<Node*> st;
st.push(root);
while (!st.empty()) {
Node *node = st.top();
st.pop();
if (node) {
ve.emplace_back(node->val);
vector<Node*> chs = node->children;
if (!chs.empty()) {
int size = chs.size();
for (int i =0; i< size; i++) {
Node *n = chs[i];
if (n) st.push(n);
}
}
}
}
reverse(ve.begin(),ve.end());
return ve;
}
};