# LeetCode 590. N叉樹的後序遍歷 (遞歸、迭代實現)

N叉樹的後序遍歷

``````/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val) {
val = _val;
}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
vector<int> ans;
vector<int> postorder(Node* root) {
dfs(root);
return ans;
}
void dfs(Node* root){
if(!root){
return ;
}
for(Node* child:root->children){
dfs(child);
}
ans.push_back(root->val);
}
};
``````

``````/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val) {
val = _val;
}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
vector<int> postorder(Node* root) {
stack<Node*> call;
vector<int> ans;
if(root){
call.push(root);
}
while(!call.empty()){
Node* par = call.top();
call.pop();
if(par){
call.push(par);
call.push(nullptr);
for(int i=par->children.size()-1;i>=0;i--){
call.push(par->children[i]);
}
}else{
ans.push_back(call.top()->val);
call.pop();
}
}
return ans;
}
};
``````