Question
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Difficulty:Easy
Category:Tree
Analyze
Solution
class Solution {
public:
vector<int> preorder(Node* root) {
if (!root) return {};
ans.push_back(root->val);
for (auto& c : root->children) preorder(c);
return ans;
}
private:
vector<int> ans;
};