N-ary Tree Preorder Traversal

迭代

/*
// 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> preorder(Node* root) {
vector<int> vec;
unordered_map<Node*,bool> m;
stack<Node*> s;
Node* node=root;
while(node||!s.empty()) {
while(node) {
vec.push_back(node->val);
s.push(node);
m[node]=true;
bool flag=false;
for(auto &child:node->children) {
if(!m.count(child)) {flag=true;node=child;break;}
}
if(!flag) node=nullptr;
}
if(!s.empty()) {
node=s.top();
bool flag=false;
for(auto& child:node->children) {
if(!m.count(child)) {flag=true;node=child;break;}
}
if(!flag) {node=nullptr;s.pop();}
}
}
return vec;
}
};

上一篇:c# – 递归到Tail递归


下一篇:python – 在金字塔中,使用遍历,如何创建动态网址?