首页 > 其他 > 详细

【leetcode】N叉树的后序遍历

时间:2020-09-15 20:52:05      阅读:56      评论:0      收藏:0      [点我收藏+]

 

/*递归*/
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;
}

 

【leetcode】N叉树的后序遍历

原文:https://www.cnblogs.com/ganxiang/p/13675214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!