#589
Easy Algorithms N ary tree preorder traversal
Stack Tree Depth-First Search
76.7% acceptance
Jan 13, 2026
3261
204
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Solution
C++
Time O(n)
Space O(1)
class Solution {
public:
vector<int> preorder(Node* root) {
if (!root) return {};
vector<int> result = {root->val};
for (Node* child : root->children) {
auto sub = preorder(child);
result.insert(result.end(), sub.begin(), sub.end());
}
return result;
}
};