我在C语言中构建二叉树时遇到了问题。我想能够将书籍添加到树中,在这些树中随后出版年份的书籍被添加到左侧,并且早期出版年份被添加在右边。我不断收到运行错误,我不确定为什么。C中的二叉树
#include <stdio.h>
#include <stdlib.h>
struct book {
char* name;
int year;
};
typedef struct tnode {
struct book *aBook;
struct tnode *left;
struct tnode *right;
} BTree;
BTree* addBook(BTree* nodeP, char* name, int year){
if(nodeP == NULL)
{
nodeP = (struct tnode*) malloc(sizeof(struct tnode));
(nodeP->aBook)->year = year;
(nodeP->aBook)->name = name;
/* initialize the children to null */
(nodeP)->left = NULL;
(nodeP)->right = NULL;
}
else if(year > (nodeP->aBook)->year)
{
addBook(&(nodeP)->left,name,year);
}
else if(year < (nodeP->aBook)->year)
{
addBook(&(nodeP)->right,name,year);
}
return nodeP;
}
void freeBTree(BTree* books)
{
if(books != NULL)
{
freeBTree(books->left);
freeBTree(books->right);
//free(books);
}
}
void printBooks(BTree* books){
if(books != NULL){
}
}
int main(int argc, char** argv) {
BTree *head;
head = addBook(head,"The C Programming Language", 1990);
/*addBook(head,"JavaScript, The Good Parts",2008);
addBook(head,"Accelerated C++: Practical Programming by Example", 2000);
addBook(head,"Scala for the impatient",2012);*/
}
“我不断收到运行错误” - 悬念是杀害我.... –
这可能是一个段错误。在这种情况下,用valgrind或类似的程序运行你的程序,你应该能够正确地调试它。在开头 –
,头指向随机存储器。尝试'BTree * head = NULL;'然后开始添加书籍。 – esskar