hi all,
i want to read strings from a file and store them in a binary search tree. i can print the strings to the screen, but when i try to store them in the tree, only last string is stored in the root of the tree, others vanish. code is below
Code:
#include <stdio.h>
//#include <iostream.h>
#include <string.h>
#include <malloc.h>
//#include <string> --cpp only
typedef struct BinaryNode
{
char* data;
struct BinaryNode* left;
struct BinaryNode* right;
}nodeType;
nodeType* root = NULL;
void insertToTree(char*);
nodeType* insertToNode(char*, nodeType*);
int isEmpty();
void printTree();
void printNode(nodeType*);
int main()
{
FILE* inputFile = fopen("deneme.txt", "r");
char* lino;
while( !feof(inputFile)){
char line[10];
lino = (char*)malloc(sizeof(char));
lino = fgets(line, sizeof(line), inputFile);
insertToTree( lino );
printf(lino);
}
printf("\n");
printf("printing whole tree \n");
printTree();
fclose(inputFile);
return 0;
}
void insertToTree(char* x)
{
root = insertToNode(x, root);
}
nodeType* insertToNode(char* x, nodeType* t){
if (t == NULL) {
t = ( nodeType * )malloc(sizeof( nodeType ) );
t->data = x;
t->left = NULL;
t->right = NULL;
}
else if(strcmp(x, t->data) < 0){
t->left = insertToNode(x, t->left);
}
else if(strcmp(x, t->data) > 0){
t->right = insertToNode(x, t->right);
}
else
;
return t;
}
void printTree(){
if( isEmpty( ) != 0)
printf( "Empty tree\n" );
else
printNode( root );
}
int isEmpty( )
{
int TRUE = 5;
int FALSE = 0;
if (root == NULL)
return TRUE;
else
return FALSE;
}
void printNode( nodeType* t )
{
if( t != NULL )
{
printNode( t->left );
printf("data: %s\n", t->data );
printNode( t->right );
}
}