I’m having trouble building a binary tree in C. I’m suppose to be able to add books to the tree where books with a later publishing year get added to the left and earlier publishing year gets added to the right. I keep getting a run error and i’m not really sure why.
#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);*/
}
One problem is that you aren’t initializing to NULL:
should be
I would recommend setting your compiler warnings higher. Your two recursive calls are not right and the compiler should have warned about them:
should be:
from a parameter passing standpoint. However, this function won’t work as it is right now since you are adding when the node pointer is NULL, which means you can’t attach a parent to a child since the parent pointer node is gone. I think the logic should look at the applicable right/left node and if NULL, add right there in the routine, else call recursively till a node is found that has a NULL right/left pointer.
Something like this: