c++
class Solution {
public:
vector<int> ans;
vector<int> preorder(Node* root) {
if (!root) return ans;
ans.push_back(root->val);
for (int i = 0; i < root->children.size(); i++) {
preorder(root->children[i]);
}
return ans;
}
};
js
var preorderImpl = function(root, ans) {
if (!root) return ;
ans.push(root.val);
for (var node of root.children) {
preorderImpl(node, ans);
}
return ;
}
var preorder = function(root) {
let ans = [];
if (!root) return ans;
preorderImpl(root, ans);
return ans;
};