解法
两种,迭代法和递归法
递归法
作者:guohaoding
链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/solution/589-ncha-shu-de-qian-xu-bian-li-liang-chong-fang-f/
/*
// 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> res;
if (root) {
helper(root, res);
}
return res;
}
void helper(Node *root, vector<int> &res) {
if (root) {
res.push_back(root->val);
for (auto child : root->children) {
helper(child, res);
}
}
}
};
迭代法
作者:buptra_prism
链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/solution/xiao-bai-shua-ti-ncha-shu-de-qian-xu-bian-li-by-bu
/*
// 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> ans;
stack<Node*> s;
if (root)
s.push(root);
while(!s.empty()) {
Node* p = s.top();
ans.push_back(p->val);
s.pop();
int len = p->children.size();
for (int i = len - 1; i >= 0; i--) {
if (p->children[i])
s.push(p->children[i]);
}
}
return ans;
}
};