Leetcode 590. N叉樹的後序遍歷(DAY 2)

錯不在我發表於2020-12-20

原題題目

在這裡插入圖片描述




程式碼實現

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     int numChildren;
 *     struct Node** children;
 * };
 */

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

#define MAX 10000
void visit(struct Node* root,int* ret,int* returnSize)
{
    if(!root)
        return;
    int i;
    for(i=0;i<root->numChildren;i++)
    {
        visit(root->children[i],ret,returnSize);
        ret[(*returnSize)++] = root->children[i]->val;
    }
    return;
}
int* postorder(struct Node* root, int* returnSize) {
    int *ret = (int*)malloc(sizeof(int) * MAX);
    *returnSize = 0;
    if(!root)
        return ret;
    visit(root,ret,returnSize);
    ret[(*returnSize)++] = root->val;
    return ret;
}

相關文章