简体   繁体   中英

level order traversal in a binary tree using queue

the following code crashes at runtime but works perfectly fine if struct node* a[10] is declared globally .Where does the problem lie.Any insight would be appreciated. Thank you!

 #include<bits/stdc++.h>
    using namespace std;
    int rear=-1;
    int front=-1;

    struct node{
        int data;
        struct node *left;
        struct node *right;
    };

    struct node *newnode(int d){
        struct node* node1=new node;
        node1->data=d;
        node1->left=NULL;
        node1->right=NULL;
        return(node1);
    }

    void enqueue(struct node* a[],struct node* tempnode){
        rear++;
        a[rear]=tempnode;
    }

    struct node* dequeue(struct node* a[]){
       front++;
      return a[front];
    }

    void bfs(struct node* root,struct node* a[]){
        struct node *tempnode=root;
        while(tempnode){
            cout<<tempnode->data;
            if(tempnode->left)
                enqueue(a,tempnode->left);
            if(tempnode->right)
                enqueue(a,tempnode->right);
            tempnode=dequeue(a);
        }
    }

    main() {
        struct node* a[10];

        struct node* root=newnode(1);
        root->left=newnode(2);
        root->right=newnode(3);
        root->left->left=newnode(-1);
        root->left->right=newnode(0);
        bfs(root,a);
    }

http://www.geeksforgeeks.org/level-order-tree-traversal/

Initialize the array "a" -

int main() {
    struct node* a[10] = {NULL};

The problem is not occurring when struct node* a[10] is declared globally because global variables are initialized automatically.

You forget to initialize a :

struct node* a[10]{};

so your dequeue will indeed return nullptr once your queue is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM