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].
分析:
典型的树遍历
代码:
/*
// 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叉树为例,详细展示了算法的具体实现过程。
485

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



