# c/c++ leetcode N叉树的前后遍历

## 前序遍历

### 解法一: 递归

class Solution {
public:
vector<int> preorder2(Node* root) {
vector<int> temp;
if (root == NULL) return temp;

return DLR(root,temp);

}
private:
//DLR - 是前序遍历
vector<int> DLR(Node* root,vector<int>& temp);
};

vector<int> Solution::DLR(Node* root,vector<int>& temp){
if(root == NULL) return temp;

temp.push_back(root -> val);

int len = root -> children.size();

for(int i = 0; i<len ; i++){
DLR(root -> children[i],temp);
}

return temp;
}


## 解法二:用stack容器

vector<int> preorder(Node* root) {
vector<int> ret;
stack<Node*> S;
Node* temp = NULL;
if(root == NULL) return ret;
S.push(root);
while(!S.empty()){
temp = S.top();
S.pop();
ret.push_back(temp -> val);

//逆向遍历孩子数组,让最右孩子先进栈
for(vector<Node*>::reverse_iterator it =temp -> children.rbegin();
it != temp -> children.rend();it++){
S.push(*it);
}
}
return ret;

}



## 后序遍历

590. N叉树的后序遍历

### 解法一: 递归

class Solution {
public:
vector<int> postorder(Node* root) {
if (root == NULL) return ans;

for (int i = 0; i < root -> children.size(); ++i){
postorder(root -> children[i]) ;
}
ans.push_back(root -> val);

return ans;
}
private:
vector<int> ans;
};


### 解法二:用stack容器

class Solution {
public:
vector<int> postorder(Node* root) {

stack<Node* > s;
deque<int> ans;
if (!root) return vector<int>();
s.push(root);
while (!s.empty() ) {
Node * temp = s.top();
s.pop();
ans.push_front(temp -> val);
//正向遍历 孩子数组;让最左孩子先进栈
for (auto loop : temp -> children) {
s.push(loop);
}
}

vector <int> ret(ans.begin(),ans.end());
return ret;
}
};


05-10 74
07-27 62
06-03 3277
11-01 442
08-17 336