zoukankan      html  css  js  c++  java
  • 【leetcode】N叉树的后序遍历

    /*递归*/
    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;
    }
  • 相关阅读:
    LOJ10092半连通子图
    LOJ104 普通平衡树
    LOJ10145郁闷的出纳员
    LOJ10144宠物收养所
    LOJ10043
    洛谷P3850 书架
    codevs 1814 最长链
    洛谷 P2022 有趣的数
    codevs 1312 连续自然数和
    noip 2010 引水入城
  • 原文地址:https://www.cnblogs.com/ganxiang/p/13675214.html
Copyright © 2011-2022 走看看