我使用队列为二进制搜索树的级别顺序遍历而编写的C代码错误

问题描述

我已经使用一个队列来优先遍历BST。

代码编译并运行。我也得到正确的答案。但是,对于最后一个节点,char重复4次,然后出现错误消息。错误消息表示我使用无效的指针调用了free()。我无法调试该问题,我们将不胜感激。

输出 F D J B E G K A C I H H H H双重自由或腐败(快速顶) 中止

//bfs - level order traversal - USING QUEUE

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

struct bstnode {
    char data;
    struct bstnode *left;
    struct bstnode *right;
};

struct bstnode *front = NULL;
struct bstnode *rear = NULL;

struct bstnode *newnode (char d);
struct bstnode *insert (struct bstnode *root,char d);
void bfs (struct bstnode *root);
void enqueue (struct bstnode *root);
struct bstnode *dequeue();

int main (void) {
    struct bstnode *root = NULL;

    root = insert (root,'F');
    root = insert (root,'D');
    root = insert (root,'B');
    root = insert (root,'A');
    root = insert (root,'E');
    root = insert (root,'C');
    root = insert (root,'J');
    root = insert (root,'K');
    root = insert (root,'G');
    root = insert (root,'I');
    root = insert (root,'H');

    bfs(root);
}

//create node
struct bstnode *newnode (char d) {
    struct bstnode *newnode = (struct bstnode *)malloc(sizeof(struct bstnode));
    newnode->data = d;
    newnode->left = newnode->right = NULL;
    return newnode;
}

//insert in bst
struct bstnode *insert (struct bstnode *root,char d) {
    if (root == NULL) {
        root = newnode(d);
    }
    else if (d <= root->data) {
        root->left = insert (root->left,d);
    }
    else {
        root->right = insert (root->right,d);
    }
    return root;
}

//level order traversal using queue
void bfs (struct bstnode *root) {
    struct bstnode *current = root;

    while (current != NULL) {
        printf("%c ",current->data);

        if (current->left != NULL) {
            enqueue(current->left);
        }
        if (current->right != NULL) {
            enqueue(current->right);
        }
        current = dequeue();  //remove char at front
    }
}

//enqueue children
void enqueue (struct bstnode *root) {
    struct bstnode *current = (struct bstnode *)malloc(sizeof(struct bstnode));
    current->data = root->data;
    current->left = root;
    current->right = NULL;

    if (front == NULL && rear == NULL) {
        front = rear = current;
        return;
    }
    rear->right = current;
    rear = current;
}

//pop element at front
struct bstnode *dequeue() {
    struct bstnode *ptr = front;

    if (front == NULL) {
        printf("there is no queue\n");
    }
    if (front == rear) {
        front = rear = ptr;
    } else {
        front = front->right;
    }

    struct bstnode *next = ptr->left;
    free(ptr);
    return next;
}

解决方法

我不确定我是否100%理解您的代码- 我一直盯着它看了20分钟, 而且我还没有尝试运行它- 但我相信我在dequeue()中遇到了一个问题。 当您仅在队列中仅剩一个节点(即front == rear)进行呼叫时, 确实

    front = rear = ptr;

其中ptr等于front。 所以这行设置了frontrear 达到他们已经拥有的价值, 而不是从队列中删除一个节点。 因此,下次您致电dequeue()时, 队列仍包含H节点- 而且即使您free,也永远不会将其与队列断开链接。

我怀疑你打算这么做

    front = rear = NULL;