Root in a binary tree is always NULL
The program should read txt, store all words in alphabetical order, and print them in order, with the number of times the word appears on the txt.
The problem is with the Insert method, because it never prints TEST, so it seems that pAux is always NULL by default. And because of this, the print method returns on the first call.
What am I doing wrong?
tree.h
#ifndef TREE_H_
#define TREE_H_
typedef struct Item{
char* key;
int no;
} TItem;
typedef struct No{
TItem item;
struct No* pLeft;
struct No* pRight;
} TNo;
void TTree_Insert (TNo**, char[]);
void TTree_Print (TNo*);
#endif
tree.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
TNo* TNo_Create (char* c){
TNo* pNo = malloc(sizeof(TNo));
pNo->item.key = malloc(sizeof(char)*strlen(c));
strcpy(pNo->item.key, c);
pNo->item.no = 1;
pNo->pLeft = NULL;
pNo->pRight = NULL;
return pNo;
}
void TTree_Insert (TNo** pRoot, char word[80]){
char* c = malloc(sizeof(char)*strlen(word));
strcpy(c, word);
TNo** pAux;
pAux = pRoot;
while (*pAux != NULL){
if (strcmp(c, (*pAux)->item.key) < 0) pAux = &((*pAux)->pLeft);
else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight);
else{
(*pAux)->item.no++;
return;
}
}
*pAux = TNo_Create(c);
return;
}
void TTree_Print (TNo *p){
if (p == NULL) return;
TTree_Print (p->pLeft);
printf("%s - %d", p->item.key, p->item.no);
TTree_Print (p->pRight);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"
int main(){
TNo* pRoot = NULL;
FILE* txt = fopen("Loremipsum.txt", "r");
char aux[80];
int c, x = 0;
while ((c = fgetc(txt)) != EOF){
while (!(isalpha((char)c))) c = fgetc(txt);
while (isalpha((char)c)) {
if (isupper((char)c)) c = c+32;
if (islower((char)c)) aux[x++] = (char)c;
c = fgetc(txt);
}
aux[x] = '\0';
TTree_Insert(&pRoot, aux);
x = 0;
aux[0] = '\0';
}
TTree_Print(pRoot);
fclose(txt);
return 0;
}
source to share
I haven't looked at all of your code. I will only answer your question. You should pass pRoot to TTree_Insert by reference. Otherwise, you are passing your copy to the function, and any changes to the copy inside the function do not affect the original value.
for example
void TTree_Insert ( TNo **pRoot, char word[80] ){
char* c = malloc(sizeof(char)*strlen(word) + 1 ); // <==
strcpy( c, word ); // <==
TNo* pAux;
pAux = *pRoot;
//...
And basically you have to call a function like
TTree_Insert( &pRoot, aux );
Note that you need to configure all other function codes. for example
void TTree_Insert( TNo **pRoot, const char word[80] )
{
char* c = malloc( sizeof( char ) * strlen( word ) + 1 );
strcpy( c, word );
TNo **pAux = pRoot;
while ( *pAux != NULL )
{
printf("TESTE");
if ( strcmp(c, ( *pAux )->item.key ) < 0 )
{
pAux = &pAux->pLeft;
}
else if ( strcmp(c, ( *pAux )->item.key ) > 0 )
{
pAux = &pAux->pRight;
}
else
{
( *pAux )->item.no++;
break;
}
}
if ( *pAux == NULL ) *pAux = TNo_Create(c);
return;
}
I hope this works. :)
source to share