[英]Binary Tree in 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);*/
}
您正在尝试访问未初始化的指针nodeP->aBook
:
nodeP = (struct tnode*) malloc( sizeof( struct tnode ) );
(nodeP->aBook)->year = year;
malloc
分配空间。 一个问题是您没有初始化为NULL:
BTree *head;
应该
BTree *head = NULL;
我建议设置更高的编译器警告。 您的两个递归调用不正确,编译器应已对其进行警告:
addBook(&(nodeP)->left,name,year );
应该:
addBook( nodeP->left,name,year );
从参数传递的角度来看。 但是,此函数无法立即使用,因为您是在节点指针为NULL时添加的,这意味着由于父指针节点消失了,因此无法将父对象附加到子对象上。 我认为逻辑应该查看适用的右/左节点,如果为NULL,则在例程中向右添加,否则递归调用直到找到具有NULL右/左指针的节点。
像这样:
BTree *makeNode(char *name, int year)
{
// NOTE: 3 frees required for every node
BTree *nodeP = malloc( sizeof( struct tnode ) ); // 1
nodeP->aBook = malloc( sizeof(struct book) ); // 2
(nodeP->aBook)->year = year;
(nodeP->aBook)->name = malloc(strlen(name) + 1); // 3
strcpy((nodeP->aBook)->name,name);
/* initialize the children to null */
nodeP->left = NULL;
nodeP->right = NULL;
return nodeP;
}
BTree* addBook(BTree* nodeP, char* name, int year)
{
if ( nodeP == NULL )
{
nodeP = makeNode(name,year);
}
else if (year > (nodeP->aBook)->year)
{
if ( nodeP->left == NULL )
nodeP->left = makeNode(name,year);
else
addBook( nodeP->left,name,year );
}
else if(year < (nodeP->aBook)->year)
{
if ( nodeP->right == NULL )
nodeP->right = makeNode(name,year);
else
addBook( nodeP->right,name,year );
}
return nodeP;
}
void printBooks(BTree* books)
{
if (books != NULL) {
printf("book: %s %d\n",books->aBook->name,books->aBook->year);
printBooks(books->right);
printBooks(books->left);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.