leetcode -- 102

102. Binary Tree Level Order Traversal

Problem Description

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
在這裏插入圖片描述

Solution Method

基本方法,報存儲空間不足的錯誤可太無語了。 with insufficient space for

int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes)
{
    struct TreeNode *Queue[10000];
    
    returnColumnSizes[0] = (int *)malloc(sizeof(int) * 1000);
    int front = 0, rear = 0, last = 0, num = 0;
    int ** resArr = (int **) malloc (sizeof(int*) * 800);
    *returnSize = 0;
    
    if (root == NULL)
        return NULL;
    resArr[(*returnSize)++] = (int* ) malloc (sizeof(int) * 500);
    Queue[rear++] = root;
    last = rear;
    num = 0;
    while (front < rear)
    {
        if (Queue[front]->left != NULL)
            Queue[rear ++] = Queue[front]->left;
        if (Queue[front]->right != NULL)
            Queue[rear ++] = Queue[front]->right;
        resArr[(*returnSize)-1][num++] = Queue[front++]->val;
        if (front == last)
        {
            returnColumnSizes[0][(*returnSize)-1] = num;
            num = 0;
            resArr[(*returnSize)++] = (int* ) malloc (sizeof(int) * 500);
            last = rear;
        }
    }
    (*returnSize)--;
    return resArr;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章