N叉树的遍历的迭代和递归实现
1、先序遍历
//迭代
class Solution {
public:
vector<int> preorder(Node* root) {
if(root == NULL) return vector<int>();
vector<int> res;
stack<Node*> mystack;
mystack.push(root);
while(!mystack.empty()){
Node* node = mystack.top();
mystack.pop();
res.push_back(node->val);
vector<Node*> child = node ->children;
for(int i=child.size()-1;i>=0;i--){
mystack.push(child.at(i));
}
}
return res;
}
};
//递归
class Solution {
public:
vector<int> preorder(Node* root) {
if(root == NULL) return vector<int>();
vector<int> res;
dfs(root,res);
return res;
}
void dfs(Node* node,vector<int> &res){
// if(node == NULL) return;
vector<Node*> child = node->children;
res.push_back(node->val);
for(int i=0;i<child.size();i++){
dfs(child.at(i),res);
}
}
};
2、后序遍历
//迭代
class Solution {
public:
vector<int> postorder(Node* root) {
if(root == NULL) return vector<int>();
vector<int> res;
stack<Node*> mystack;
mystack.push(root);
while(!mystack.empty()){
Node* node = mystack.top();
mystack.pop();
vector<Node*> child = node->children;
res.insert(res.begin(),node->val);
for(int i=0;i<child.size();i++){
mystack.push(child.at(i));
}
}
return res;
}
};
//递归
class Solution {
public:
vector<int> postorder(Node* root) {
if(root == NULL) return vector<int>();
vector<int> res;
dfs(root,res);
return res;
}
void dfs(Node* node,vector<int> &res){
vector<Node*> child = node->children;
for(int i=0;i<child.size();i++){
dfs(child.at(i),res);
}
res.push_back(node->val);
}
};
3、层序遍历
//迭代
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if(root == NULL) return vector<vector<int>>();
vector<vector<int>> res;
queue<Node*> myqueue;
myqueue.push(root);
while(!myqueue.empty()){
int size = myqueue.size();
vector<int> levelNodes;
for(int i=0;i<size;i++){
Node* node = myqueue.front();
vector<Node*> child = node ->children;
myqueue.pop();
levelNodes.push_back(node ->val);
for(int i=0;i<child.size();i++){
myqueue.push(child.at(i));
}
}
res.push_back(levelNodes);
}
return res;
}
};
//递归
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if(root == NULL) return vector<vector<int>>();
vector<vector<int>> res;
dfs(root,0,res);
return res;
}
void dfs(Node* node,int currlevel,vector<vector<int>> &res){
//递
if(res.size() == currlevel){
vector<int> levelNodes;
levelNodes.push_back(node->val);
res.push_back(levelNodes);
}else{
res.at(currlevel).push_back(node ->val);
}
for(Node* child: node ->children){
dfs(child,currlevel+1,res);
}
}
};