繁体   English   中英

C中的BST链接列表:广度优先搜索

[英]Linked List of BST in C: Breadth First Search

我正在编写一个程序,该程序是二进制搜索树的链接列表。 我们应该在树中搜索一个数字,然后打印找到的树和行号。 因此,我们应该使用广度优先搜索功能。 我在出队功能中遇到分段错误,我不确定为什么。

这些是我的结构:

typedef struct BST {
    int value;
    int treeNum;
    struct BST* left;
    struct BST* right;
}BST;

typedef struct rootList{
    struct BST* root;
    struct rootList* next;
}rootList;

typedef struct bfsQ{
    struct BST* treeNode;
    struct bfsQ* next;
}bfsQ;

这是我的BFS功能:

void BFS(rootList* listHead, int searchValue)
{
    if(listHead->root == NULL)
    {
        printf("%d/tNO/tN/A/tN/A\n", searchValue);
    }
    else
    {
        bfsQ* newQueue = NULL;
        BST* temp = NULL;

        newQueue = malloc(sizeof(bfsQ));
        newQueue->next = NULL;
        enqueue(&newQueue, listHead->root);
        while(newQueue != NULL)
        {
            temp = dequeue(&newQueue);
            printf("Did this work?");
            if(temp->value == searchValue)
                printf("HI I WAS FOUND");
            else
            {
                if(temp->left != NULL)
                    enqueue(&newQueue, temp->left);
                if(temp->right != NULL)
                    enqueue(&newQueue, temp->right);
            }
        }
        BFS(listHead->next, searchValue);
    }
}

这是我的入队:

void enqueue(bfsQ** qHead, BST* new_tree_node)
{
    bfsQ *temp = malloc(sizeof(bfsQ));
    BST *node;
    temp->treeNode = new_tree_node;
    temp->next = *qHead;
    *qHead = temp;
    node = temp->treeNode;
    printf("%d\n", node->value);
}

这是我的出队:

BST* dequeue(bfsQ** qHead)
{
    bfsQ *temp, *first;
    BST *newBST;
    temp = (*qHead);
    while(temp->next != NULL)
    {
        printf("THIS IS NOT NULL YET\n");
        temp = temp->next;
    }
    first = temp;
    newBST = first->treeNode;
    free(temp);
    return first->treeNode;
}

我究竟做错了什么? 入队正常,但是我的出队存储不正确。

编辑:显然我需要:

“此函数实现了逐级搜索的形式或正式称为BREADTH FIRST SEARCH。->此函数在二叉树中搜索给定值,并通过在每个二叉树中搜索第1级,然后移动如果无法在1级上找到该值,则转到2级,依此类推。->基本上,您必须在所有二叉树中一次在链接列表中一次搜索一个给定值。”

因此,我不确定是否需要逐行搜索整棵树,然后继续前进或查看每棵树。

从我对代码的肤浅印象来看,它看起来通常还可以(尽管我会以不同的方式实现某些部分),但是dequeue()的最后几行肯定是错误的:

first = temp;
newBST = first->treeNode;
free(temp);
return first->treeNode;

在最后一行访问first->treeNode会带来灾难性的后果: first保存一个已经释放的地址( tempfirst指向相同的内存位置)。 我认为您想改为返回newBST

return newBST; 

您最好first扔掉,因为它似乎没有用,然后将其转换为:

newBST = temp->treeNode;
free(temp);
return newBST;

暂无
暂无

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

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