Leetcode 剑指 Offer 32 - I 从上到下打印二叉树

这道题主要考察对各种数据结构间的相互切换。
具体分析参考剑指offer32.

时间和内存消耗以及源代码如下:
Leetcode 剑指 Offer 32 - I 从上到下打印二叉树_第1张图片

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

int* levelOrder(struct TreeNode* root, int* returnSize){

    if  (root == NULL)
    {
        * returnSize    =   0;
        return;
    }

    struct TreeNode**   pstart;
    pstart  =   (struct TreeNode**) malloc (2*1000*sizeof(struct TreeNode*));
    int*    deque;
    deque =   (int*)malloc(2*1000*sizeof(int));
    int start_pnum   =   0;
    int end_pnum     =   0;

    pstart[end_pnum] =   root;   
    deque[end_pnum]  =   root->val;
    end_pnum++;

    while(start_pnum != end_pnum)
    {
        if  (root)
        {
            if  (pstart[start_pnum]->left)
            {
                pstart[end_pnum]    =   pstart[start_pnum]->left;
                deque[end_pnum]     =   pstart[end_pnum]->val;
                end_pnum++;
            }
            if  (pstart[start_pnum]->right)
            {
                pstart[end_pnum]    =   pstart[start_pnum]->right;
                deque[end_pnum]     =   pstart[end_pnum]->val;
                end_pnum++;
            }
            start_pnum++;
        }
    }
    
    *returnSize =   start_pnum;

    return  deque;
}

你可能感兴趣的:(leetcode,算法,c语言)