我正在尝试将一些内容插入二叉树中,并且我想通过使用有序打印函数来检查里面有什么。 “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/