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?
分析:前序遍历
代码:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
static const auto __ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> ress;
stack<Node*> res;
if(!root)
return ress;
Node* temp;
res.push(root);
while(!res.empty())
{
temp = res.top();
res.pop();
for(int i=0;i<temp->children.size();++i)
res.push(temp->children[i]);
ress.push_back(temp->val);
}
reverse(ress.begin(), ress.end());
return ress;
}
};
本文介绍了一种不使用递归的迭代方法来实现N叉树的后序遍历,通过栈结构逆序存储节点值再反转,达到与递归方法相同的效果。示例中以3叉树为例,详细解释了算法的具体实现过程。
496

被折叠的 条评论
为什么被折叠?



