C language binary tree layer order traversal -- malloc two-dimensional array to store the results of each layer

This question comes from leetcode  102 Binary Tree Level Order Traversal

1. Problem description

Given a binary tree, return a level-order traversal of its node values. (that is, from left to right, step by step)
[Example]
Given a binary tree [3,9,20,null,null,15,7],
    3
   / \
  9 20
    / \
   15 7
Return to level order traversal:
[
  [3 ],
  [9,20],
  [15,7]

]

Second, the key points of problem-solving ideas

1. With the help of queues, layer-order traversal is realized

2. Use two constants to record the current layer element value cur_layer_count and the next layer element value next_layer_count. Each time an element is popped, the current layer element value is decremented; until the current layer element value is reduced to 0, it means that the layer element output is completed, Then the number of layers can be layer++

3. The malloc method of a two-dimensional array:

    int** result = (int**)malloc(layer*sizeof(int*));  //先malloc行

    for( i=0; i<layer; i++ )

        result[i] = (int*)malloc( (*columnSizes)[i]) * sizeof(int)); //How many columns are there in each row of malloc

4. Pay attention to the meaning of the parameters in the title:

** columnSizes: used to store the length         of the result of each layer after layer order traversal
        * returnSize: used to return a total of how many layers
        so the final returned result needs a custom two-dimensional array to store

3. Algorithm code

1. Queue data structure definition

/**BFS will use the queue data structure**/
/**Circular queue**/
typedef struct
{
    struct TreeNode data[1000];
    int front; //head pointer
    int rear; //tail pointer, if the queue is not empty, it points to the position after the last element at the end of the queue
} sqqueue;

// queue initialization
void InitQueue(SqQueue *Q)
{
    Q->front = 0;
    Q->rear = 0;
}
// enqueue
bool EnQueue(SqQueue *Q, struct TreeNode e)
{
    //Check if the queue is full
    if( ( Q->rear+1 ) % 1000 == Q->front )
        return false;
    Q->data[Q->rear]=e;
    Q->rear = (Q->rear+1)%1000;
    return true;
}
//dequeue---delete the first element of the team and assign it to e
struct TreeNode* DeQueue(SqQueue *Q, struct TreeNode* e)
{
    //Check if the queue is empty
    if( Q->front == Q->rear )
        return NULL;
    *e = Q->data[Q->front];
    Q->front = (Q->front+1)%1000;
    return e;
}
// queue is empty
bool isEmptyQueue(SqQueue *Q)
{
    return Q->front == Q->rear?true:false;
}

2. Main algorithm part

/******************************************
Author:tmw
date:2018-5-5
******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

/**
The level order traversal of the binary tree relies on the data structure of the queue - the principle is the same as that of BFS
** columnSizes: used to store the length of the result of each layer after layer order traversal
* returnSize: how many layers are used to return
**/
int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize)
{
    /**Apply and initialize the queue**/
    SqQueue q;
    InitQueue(&q);

    int cur_layer_count = 0; /**Record the number of nodes in the current layer**/
    int next_layer_count = 0; /**Record the next layer node**/
    int layer = 0; /**Record layer number**/

    /**The temp array is used to temporarily store the number of elements in each layer**/
    int* temp = (int*)malloc(1000*sizeof(int));
    temp[0] = 1;

    /**The first traversal of the binary tree: malloc constructs a two-dimensional array corresponding to the size of the result**/
    if( root != NULL )
    {
        struct TreeNode p; /**Continue to dequeue elements**/

        /**First enqueue the current node**/
        EnQueue(&q,*root);

        cur_layer_count++;

        /**BFS---Construct a two-dimensional array for layer-order traversal**/
        while( !isEmptyQueue(&q) )
        {
            /** Dequeue the element in the current queue and enqueue other nodes associated with it**/
            DeQueue(&q,&p);

            cur_layer_count--;

            // join the associated node
            if( p.left )
            {
                EnQueue(&q,*(p.left));
                next_layer_count++;
            }
            if( p.right )
            {
                EnQueue(&q,*(p.right));
                next_layer_count++;
            }
            if( cur_layer_count == 0 ) //One layer has been traversed
            {
                layer++;
                printf("%d\n",layer);
                temp[layer] = next_layer_count;
                cur_layer_count = next_layer_count;
                next_layer_count = 0;
            }
        }
    }

    /**
        pass the number of layers to the formal parameter
        ** columnSizes: used to store the length of the result of each layer after layer order traversal
        * returnSize: how many layers are used to return

        So the final result requires a custom two-dimensional array to store
    **/
    *returnSize = layer;

    *columnSizes = (int*)malloc(layer*sizeof(int));
    int i;
    for( i=0; i<layer; i++ )
        (*columnSizes)[i] = temp[i];
    free(temp);

    /**A two-dimensional array of final results---result**/
    int** result;
    result = (int**)malloc(layer*sizeof(int*));
    for( i=0; i<layer; i++ )
        result[i] = (int*)malloc((*columnSizes)[i]*sizeof(int));


    /**Second traversal of the binary tree: store the result of the layer order into the constructed two-dimensional array result**/
    if( root != NULL )
    {
        struct TreeNode p; /**Continue to dequeue elements**/

        int cur_layer_count = 0; /**Record the number of nodes in the current layer**/
        int next_layer_count = 0; /**Record the next layer node**/
        int layer = 0; /**Record layer number**/
        int j=0;

        /**First enqueue the current node**/
        EnQueue(&q,*root);

        cur_layer_count++;

        /**BFS---pass by value**/
        while( !isEmptyQueue(&q) )
        {
            /** Dequeue the element in the current queue and enqueue other nodes associated with it**/
            DeQueue(&q,&p);
            cur_layer_count--;

            result[layer][j] = p.val;
            j++;

            /**Association node enqueue**/
            if( p.left )
            {
                EnQueue(&q,*(p.left));
                next_layer_count++;
            }
            if( p.right )
            {
                EnQueue(&q,*(p.right));
                next_layer_count++;
            }
            if( cur_layer_count == 0 ) /**One layer has been traversed**/
            {
                layer++; /**Enter the next layer after traversing the current layer**/
                cur_layer_count = next_layer_count;
                next_layer_count = 0;
                j=0; /**The storage of the next layer starts from position 0 of the array**/
            }
        }
    }

    /** result print**/
    int ii, jj;
    for (ii = 0; ii <layer; ii ++)
    {
        for(jj=0;jj<(*columnSizes)[ii];jj++)
            printf("%d ",result[ii][jj]);
        printf("\n");
    }

    return result;
}

4. Execution results

leetcode C accept

                                                                                                              There is still a dream, if it comes true~~~ヾ(◍°∇°◍)ノ゙~~~



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325908236&siteId=291194637