leetcode簡単問題107.ツリー階層遍歴|(C)

1790 ワード

タイトルの概要:
ツリーを指定し、ノード値の下から上への階層遍歴を返します.(すなわち、リーフノードのある層からルートノードのある層まで、層ごとに左から右へ遍歴する)
例えば、所与の二叉木[3,9,20,null,null,15,7]は、
    3   /\  9  20    / \   15   7
下から上への階層の遍歴を返します.
[   [15,7],   [9,20],   [3] ]
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
//            
//         

#define maxSize 1010 

int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    int front,rear;
    front = rear = 0;
    struct TreeNode* que[maxSize]; //      
    int** res = (int**)malloc(sizeof(int*)*maxSize); //         
    *returnSize = 0; //          
    *returnColumnSizes = (int*)malloc(sizeof(int)*maxSize); 
                     //       res       
    if(root)
    {
        rear = (rear+1)%maxSize;
        que[rear] = root;//     
    }
    while(front != rear)//          
    {
        (*returnColumnSizes)[*returnSize] = rear - front;
        res[*returnSize] = (int*)malloc(sizeof(int)*(*returnColumnSizes)[*returnSize]);
        for(int i=0; ival;
            if(cur->left){
                rear = (rear+1)%maxSize;
                que[rear] = cur->left;
            }
            if(cur->right){
                rear = (rear+1)%maxSize;
                que[rear] = cur->right;
            }
        }
        (*returnSize)++; 
    }

    int i = 0, j = *returnSize - 1;
    while(i