我已经实现了一个二叉树及其 BFS 遍历。程序如下:
struct elemq{
int ele;
struct elemq *left;
struct elemq *right;
};
struct que{
struct elemq *ss;
struct que *next;
};
void qinsert(struct elemq *ptr){
struct que *node;
node = (struct que *)malloc(sizeof(struct que));
if(front == NULL && rear == NULL){
node->ss = ptr;
node->next = NULL;
front = node;
rear = node;
}
else{
node->ss = ptr;
node->next = NULL;
rear->next = node;
rear = node;
}
}
struct elemq *qdelete(){
if(front == NULL && rear == NULL){
cout << "No elements to delete\n";
exit(0);
}
struct elemq *dd = front->ss;
struct que *ddd = front;
front = front->next;
free(ddd);
return dd;
}
int isempty(){
if(front == NULL && rear == NULL){
return 1;
}
else{
return 0;
}
}
void bfs(){
qinsert(root);
struct elemq *fff;
while(!isempty()){
fff = qdelete();
cout << fff->ele << "\n";
if(fff->left != NULL){
qinsert(fff->left);
}
if(fff->right != NULL){
qinsert(fff->right);
}
}
}
虽然代码很长,但是很容易理解。elemq 结构是树中节点的结构。que 是我用来实现 bfs 的队列。q insert 是将元素插入队列,qdelete 删除队列中的元素。isempty() 用于检查队列是否为空。程序显示根元素,然后给出分段错误。请帮忙。挣扎了一段时间。