Aero Xavier Mazter Aero Xavier Mazter - 1 month ago 7
C Question

Why does it say that the tree is null even though I inserted values?

I am trying to work on a binary search tree program. This is my main program. Every time I try to print Inorder traversal of the values I inserted into the tree, the printInorder function says that it's empty or null. I'm aware that the root is initialized to NULL but how do I let function know that the tree is not empty?

void main()
{
int pgS, ch;
char chT[MAX], chT2[MAX];
treePtr root = NULL;

menu();
scanf("%d",&ch);

switch(ch)
{
case 1:
fflush(stdin);
printf("\nName of the Content: ");
gets(chT);
printf("\nPage of the content above: ");
scanf("%d",&pgS);
insert(root,pgS,chT);
system("cls");
main();
break;
case 2:
system("cls");
printInOrder(root);
Sleep(5000);
main();
break;
case 3:
printf("\nSearch Content: ");
gets(chT2);
search(root,chT2);
}

getch();
}


Some of the functions, maybe it can help.

treePtr insert(treePtr p, elementType noP, char *Incontent){ //insert elements in the tree
if(p==NULL) {p=createTree(Incontent,noP);}
else {
if(p->pages > noP){
p->left=insert(p->left,noP,Incontent);
p->part=Incontent;
p->pages=noP;
}
else if (p->pages <noP){
p->right=insert(p->right,noP,Incontent);
p->part=Incontent;
p->pages=noP;

}
} return p;
}
void printInOrder(treePtr p){
if (p == NULL){printf("Empty");}
else {
printInOrder(p->left);
printf("\nTABLE OF CONTENTS\n%s\t\t %d ", p->part,p->pages);
printInOrder(p->right);
}
}

Answer

Your insert function calls createTree to assign a new instance to the p variable, but you don't assign this variable to the root variable in your main function, so root remains NULL after the function returns (i.e. root = insert(root, ...) would work).

Or, you could simply create the root node tree before calling insert (i.e. root = createTree(...);). Nevertheless, a main function recursively calling itself is a bad idea.