我在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