递归:
void dfs(struct Node* root, int* ans, int* count){
if(root == NULL) return ;
ans[(*count)++] = root->val;
for(int i = 0; i < root->numChildren; i++){
dfs(root->children[i], ans, count);
}
return;
}
int* preorder(struct Node* root, int* returnSize) {
int* ans = (int *)malloc(sizeof(int) * 10000);
int count = 0;
dfs(root, ans, &count);
*returnSize = count;
return ans;
}
迭代:
int* preorder(struct Node* root, int* returnSize){
*returnSize = 0;
if(root == NULL) return NULL;
int* ans = (int *)malloc(sizeof(int) * 10000);
struct Node** sta = (struct Node**)malloc(sizeof(struct Node*) * 10000);
int top = -1;
sta[++top] = root;
while(top != -1){
struct Node* p = sta[top--];
ans[(*returnSize)++] = p->val;
for(int i = p->numChildren - 1; i >= 0; i--){
sta[++top] = p->children[i];
}
}
return ans;
}