题目链接https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
解题代码
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> preNum;
pre(root, preNum);
return preNum;
}
void pre(Node* root, vector<int>& nums){
if(root==NULL){
return;
}
nums.push_back(root->val);
if(root->children.size()!=0){
int n = root->children.size();
for(int i=0; i<n; i++){
pre(root->children[i], nums);
}
}
}
};
运行结果