# 589. N-ary Tree Preorder Traversal

Given an n-ary tree, return the  preorder  traversal of its nodes’ values.

For example, given a `3-ary` tree:

Return its preorder traversal as: `[1,3,5,6,2,4]`.

Note:

Recursive solution is trivial, could you do it iteratively?

``````class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> res;
helper(root, res);
return res;
}
void helper(Node* node, vector<int>& res) {
if (!node) return;
res.push_back(node->val);
for (Node* child : node->children) {
helper(child, res);
}
}
};
``````

``````class Solution {
public:
vector<int> preorder(Node* root) {
if (!root) return {};
vector<int> res;
stack<Node*> st{{root}};
while (!st.empty()) {
Node* t = st.top(); st.pop();
res.push_back(t->val);
for (int i = (int)t->children.size() - 1; i >= 0; --i) {
st.push(t->children[i]);
}
}
return res;
}
};
``````

Binary Tree Preorder Traversal

N-ary Tree Level Order Traversal

N-ary Tree Postorder Traversal

https://leetcode.com/problems/n-ary-tree-preorder-traversal/

https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/147955/Java-Iterative-and-Recursive-Solutions

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation