繁体   English   中英

使用队列在二叉树中进行级别顺序遍历

[英]level order traversal in a binary tree using queue

下面的代码在运行时崩溃,但是如果全局声明struct node * a [10]则可以正常工作。问题出在哪里。 谢谢!

 #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/

初始化数组“ a”-

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

全局声明结构节点* a [10]时不会发生此问题,因为全局变量是自动初始化的。

你忘了初始化a

struct node* a[10]{};

因此,一旦队列为空, dequeue确实会返回nullptr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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