• 【leetcode】107. 二叉树的层次遍历 II


    //C语言DFS
    void recursion(struct TreeNode* root,int** arr,int* ColumnSizes,int cur,int* returnSize){
        if(!root) {
            if(cur>*returnSize) *returnSize=cur;
            return;
        }
        if(ColumnSizes[1000-cur]==0){
            arr[1000-cur]=(int*)calloc(1001,sizeof(int));
        }
        arr[1000-cur][ColumnSizes[1000-cur]++]=root->val;
        recursion(root->left,arr,ColumnSizes,cur+1,returnSize);
        recursion(root->right,arr,ColumnSizes,cur+1,returnSize);    
    }
    int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
        int** arr=(int**)calloc(1001,sizeof(int*));
        *returnSize=0;
        *returnColumnSizes=(int*)calloc(1001,sizeof(int));
        recursion(root,arr,*returnColumnSizes,0,returnSize);
        (*returnColumnSizes) += 1000-*returnSize+1;
        return arr+1000-*returnSize+1;
    }
    //C语言BFS
    int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
        int** levelOrder = malloc(sizeof(int*) * 2001);
        *returnColumnSizes = malloc(sizeof(int) * 2001);
        *returnSize = 0;
        if (!root) {
            return levelOrder;
        }
        struct TreeNode** q = malloc(sizeof(struct TreeNode*) * 2001);
        int left = 0, right = 0;
        q[right++] = root;
        while (left < right) {
            int len = right - left;
            int* level = malloc(sizeof(int) * len);
            (*returnColumnSizes)[*returnSize] = len;
            for (int i = 0; i < len; ++i) {
                struct TreeNode* node = q[left++];
                level[i] = node->val;
                if (node->left != NULL) {
                    q[right++] = node->left;
                }
                if (node->right != NULL) {
                    q[right++] = node->right;
                }
            }
            levelOrder[(*returnSize)++] = level;
        }
        for (int i = 0; 2 * i < *returnSize; ++i) {
            int* tmp1 = levelOrder[i];
            levelOrder[i] = levelOrder[(*returnSize) - i - 1];
            levelOrder[(*returnSize) - i - 1] = tmp1;
            int tmp2 = (*returnColumnSizes)[i];
            (*returnColumnSizes)[i] = (*returnColumnSizes)[(*returnSize) - i - 1];
            (*returnColumnSizes)[(*returnSize) - i - 1] = tmp2;
        }
        return levelOrder;
    }
  • 相关阅读:
    【洛谷P2860】冗余路径
    【CF1042D】Petya and Array 离散化+树状数组
    【洛谷P2127】序列排序
    【洛谷P4462】异或序列
    【SPOJ10707】COT2
    【CF1119D】Frets On Fire
    【CF1119E】Pavel and Triangles
    【洛谷P1903】数颜色
    hdu 3488(KM算法||最小费用最大流)
    hdu 1853(拆点判环+费用流)
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14060934.html
Copyright © 2020-2023  润新知