在 C 中创建和显示基本 BST

标签 c pointers binary-search-tree

我确信我犯了一些愚蠢的错误,希望有人能帮助我并澄清我的一些基本概念。

这是我用 C 语言创建和打印基本 BST 的代码:

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

typedef struct bst
{
    int value;
    struct bst *left;
    struct bst *right;
}T;

T *temp=NULL, *newnode;
T *tree; // had globally declared as NULL previously

T* createnode(int val)
{
    newnode=(T*)malloc(sizeof(T));
    if(newnode==NULL)
    {
        printf("Memory not allocated! \n");
    }
    else
    {
        newnode->value=val;
        newnode->right=NULL;
        newnode->left=NULL;
    }
    return newnode;
}

T * insert_tree(T *tree, int val)
{
    if(tree==NULL)
    {
        newnode=createnode(val);
        tree=newnode;
        return tree;
    }

    if (val < tree->value)
    {
        tree->left=insert_tree(tree->left,val);
    }
    else if(val > tree->value)
    {
        tree->right=insert_tree(tree->right, val);
    }
    return tree;
}

void display_preorder(T *tree) //changed to accept parameter
{
    if(tree)
    {
        printf("%d \n", tree->value);
        display_preorder(tree->left);
        display_preorder(tree->right);
    }
}

int main(void)
{
    insert_tree(tree,34);
    insert_tree(tree,45);
    insert_tree(tree,88);
    insert_tree(tree,87);
    display_preorder();
    return 0;
}

它运行和执行没有错误,但是输出屏幕是空白的。

有人可以指出错误和错误吗?

谢谢。

最佳答案

问题出在 insert_tree 函数中。 因为您的函数仅获取树的指针而不是指向您返回值的指针的指针。 所以,总的来说,你应该把树放在等于函数的地方。 您的函数按值而不是按引用获取树指针。 像这样:

int main(void)
{
    tree = insert_tree(tree, 34);
    tree = insert_tree(tree, 45);
    tree = insert_tree(tree, 88);
    tree = insert_tree(tree, 87);
    display_preorder(tree);
    getchar();
    return 0;
}

关于在 C 中创建和显示基本 BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306258/

相关文章:

c - 丢失数据包(Windows NDIS 驱动程序过滤器)

c - 如何在两个应用程序之间共享一个共享库(*.so)实例

c - 函数指针数组错误: Initialization from incompatible pointer type

c++ - 带数组指针的 std::unique_ptr

来自 "Pro Coder"示例的 Python 二叉搜索树

c - 这个 strlen() 实现有什么问题吗?

C 链接错误 : undefined reference to 'main'

c++ - 返回 const 模板类型的模板函数

c - 打印 BST 中的 n 个最大值

algorithm - logN 中的搜索、插入、删除和删除最后操作