c - 二叉搜索树按顺序打印

标签 c binary-search-tree

我正在尝试将一些内容插入二叉树中,并且我想通过使用有序打印函数来检查里面有什么。 “print_bst_node(root->left);”似乎引发了异常上面写着“抛出异常:读取访问冲突。”每次我运行该程序时。这个函数是不是有什么问题?

编辑,添加 insert_bst 包装函数。

//bst.h

    typedef struct bstNode { //pointer to the bst 
        long data;  //storing long data types from -2,147,483,648 to 2,147,483,647
        List courses; //this is the list of courses 
        struct bstNode *left; //left child of the tree
        struct bstNode *right; //right child of the tree
    } *BSTNodePtr;

    typedef struct bst {
        BSTNodePtr root; //points to the root of the tree 
    } BST;

//bst.c 

    void print_bst_node(BSTNodePtr root) {
        if (root != NULL) {
            print_bst_node(root->left);
            printf("%ld ", root->data);
            print_bst_node(root->right);
        }
        else {
            printf("Nothing to see here");
        }
    }

BSTNodePtr insert_bst_node(BSTNodePtr self, long n) { 
    if (self == NULL) {
        self = malloc(sizeof *self);
        self->data = n;
        self->courses = new_list(); //creates a new linked list in the binary search tree nodes.
        self->left = self->right = NULL;
    }
    else if (n < self->data) {
        self->left = insert_bst_node(self->left, n);
    }
    else if (n > self->data) {
        self->right = insert_bst_node(self->right, n);
    }
    return self;
}


void insert_bst(BST *self, long n) { //wrapper function for insert_bst_node
    self->root = insert_bst_node(self->root, n);
} 
//main.c 

void add_to_bst(BST *self) { 
    long input = 0;

    printf("Enter student ID\n");
    scanf("%ld", &input);
    insert_bst(self, input);
    print_bst_node(self);
}

最佳答案

出现此问题的原因是您将不兼容的指针作为参数传递给 print_bst_node() 函数。 print_bst_node() 参数的类型为 BSTNodePtr:

void print_bst_node(BSTNodePtr root) {

并且您将 self 传递给它:

print_bst_node(self);

这是一个指向 BST 类型的指针:

void add_to_bst(BST *self) { 

相反,您应该将 self->root 传递给 print_bst_node():

print_bst_node(self->root);

编译器必须针对传递不兼容的指针类型抛出警告消息。

关于c - 二叉搜索树按顺序打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50037785/

相关文章:

algorithm - 如何验证二叉搜索树?

c - if..else..if..else 代码无法正常工作(用 C 语言编码)

c - 如何在特定范围内创建新的随机整数

android - 使用 Android NDK 为 x86 编译 FFmpeg 3.1.1

c++ - BST 搜索函数在一台机器上返回真,在另一台机器上返回假

C++ 二叉树 : Return the number of descendants of a node. 叶子有零。如果未找到 TreeData,则返回 -1

c - 如何用coq证明c程序的正确性

两个连接的套接字可以监听不同的端口吗?

C++ 如何生成 10,000 个唯一的随机整数以存储在 BST 中?

c - C中的BST遍历