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:
/*
// 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;
};