版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35747066/article/details/89455210
590. N-ary Tree Postorder Traversal
Easy
25736FavoriteShare
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;
}
};
*/
class Solution {
public:
void postorder(vector<int>& Res,Node* root){
s.push(root);
while(!s.empty()){
Node* tmp = s.top();
s.pop();
for(auto child : tmp->children){
s.push(child);
}
Res.push_back(tmp->val);
}
reverse(Res.begin(),Res.end());
}
vector<int> postorder(Node* root) {
vector<int> Res;
if(root == NULL){return Res;}
postorder(Res,root);
return Res;
}
private:
vector<int> Result;
stack<Node*> s;
};