Tree: Level Order Traversal

  • [deleted]
    + 0 comments

    First your answer is in C not C++ which is different. By looking at your code I guess you're a beginner so I suggest you to read this : C Programming (second edition) by Brian and Dennis

    And for pointers exclusively : Better understand of advanced pointers (C)

    As for the solution I mimick the C++ solution of this comment section.

    Side Note: This is my solution in C and this is not the complete code to run it but only the interesting part. (I highly recommend to be able to deal with pointers)

    #include<stdio.h> // Library for basic functions
    #include<stdlib.h> // String functions and memory allocations function
    
    // The presuming structure used in this exercise
    typedef struct node { 
            char *data;
            struct node *left;
            struct node *right;
    } node;
    
    // Example of memory allocation function
    node *getNodeSpace(void){
            node *s = NULL;
            if((s = (node *) malloc(sizeof(node))) == NULL)
                    exit(1);
    return s;
    }
    
    // The function in C
    void LevelOrder(node *root){
            int i = 0; // allow to go through the storing array
            int x = 0; // count the number of node
            node *temp; // node holder
            node **base; // pointer to storing array
            node **s; // storing array
    
            if(root != NULL){
                    *s = root;
                    base = s;
                    ++x;
            }
    
            while((temp = *(base+i)) != NULL && x){
                    printf("%s\n", temp->data);
                    if(temp->left)
                            if(*++s = getNodeSpace()){
                                    (*s)->data = temp->left->data;
                                    (*s)->left = temp->left->left;
                                    (*s)->right = temp->left->right;
                                    ++x;
                            }
                    if(temp->right)
                            if(*++s = getNodeSpace()){
                                    (*s)->data = temp->right->data;
                                    (*s)->left = temp->right->left;
                                    (*s)->right = temp->right->right;
                                    ++x;
                            }
                    ++i;
                    --x;
            }
    }
    

    See ya!