我在用 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);*/
}