递归1
class Solution {
public:
vector<int>res;
vector<int> postorder(Node* root) {
if(root==nullptr) return {};
for(int i=0;i<root->children.size();i++){
postorder(root->children[i]);
}
res.push_back(root->val);
return res;
}
};
递归2
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int>vec;
helper(root,vec);
return vec;
}
void helper(Node* &root,vector<int> &vec){
if(root==nullptr)return;
for(auto ch : root->children){
helper(ch,vec);
}
vec.push_back(root->val);
}
};
非递归
class Solution {
public:
vector<int> postorder(Node* root) {
if(root==nullptr) return {};
vector<int>vec;
stack<Node*>stk1;
stack<Node*>stk2;
stk1.push(root);
while(!stk1.empty()){
Node* cur=stk1.top();
stk1.pop();
stk2.push(cur);
for(auto ch : cur->children){
stk1.push(ch);
}
}
while(!stk2.empty()){
vec.push_back(stk2.top()->val);
stk2.pop();
}
return vec;
}
};