/*递归*/
void func(struct Node* root, int* arr,int* returnSize)
{
arr[(*returnSize)++] = root->val;
for (int i=0; i<root->numChildren; i++)
{
func(root->children[i],arr,returnSize);
}
}
int* preorder(struct Node* root, int* returnSize) {
*returnSize=0;
if (!root) return NULL;
int* arr = (int*)calloc(10000,sizeof(int));
func(root,arr,returnSize);
return arr;
}
/**
* 迭代
**/
#define MAX_SIZE 10240
int* preorder(struct Node* root, int* returnSize) {
int i, top = -1, *result = (int*)calloc(MAX_SIZE, sizeof(int));
struct Node *p, **stack = (char**)malloc(sizeof(struct Node*) * MAX_SIZE);
*returnSize = 0;
if (root == NULL) return result;
stack[++top] = root;
while (top != -1) {
p = stack[top--];
result[(*returnSize)++] = p->val;
// 从最后一个孩子开始入栈
for (i = p->numChildren - 1; i >= 0; i--)
stack[++top] = p->children[i];
}
return result;
}