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;
}
};