[LeetCode][589] N-ary Tree Preorder Traversal
题意:给定一个n叉树,返回它的前序遍历
1.循环
vector<int> preorder(Node *root)
{
if (root == nullptr)
{
return vector<int>{};
}
stack<Node *> s;
vector<int> res;
s.push(root);
while (!s.empty())
{
Node *temp = s.top();
s.pop();
for (int i = temp->children.size() - 1; i >= 0; i--)
{
s.push(temp->children[i]);
}
res.push_back(temp->val);
}
return res;
}
2.递归
private:
vector<int> res;
public:
vector<int> preorder(Node *root)
{
if (root == nullptr)
{
return res;
}
dfs(root);
return res;
}
void dfs(Node *root)
{
if (root == nullptr)
{
return;
}
res.push_back(root->val);
vector<Node *> c = root->children;
for (auto child : c)
{
dfs(child);
}
}