/*递归*/ void func(struct Node* root, int* arr,int* returnSize) { for (int i=0; i<root->numChildren; i++) { func(root->children[i],arr,returnSize); } arr[(*returnSize)++] = root->val; } int* postorder(struct Node* root, int* returnSize) { *returnSize=0; if (!root) return NULL; int* arr = (int*)calloc(10000,sizeof(int)); func(root,arr,returnSize); return arr; }
/*迭代*/ int* postorder(struct Node* root, int* returnSize) { *returnSize=0; if (!root) return NULL; int* arr = (int*)calloc(10000,sizeof(int)); struct Node *p, **stack = (struct Node**)malloc(10000*sizeof(struct Node*)); int top=-1; stack[++top] = root; while(top != -1) { p = stack[top]; if (p->numChildren == 0) { arr[(*returnSize)++] = p->val; top--; } while(p->numChildren) stack[++top] = p->children[--(p->numChildren)]; } return arr; }
原文:https://www.cnblogs.com/ganxiang/p/13675214.html