#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <conio.h>
#include <stdlib.h>
struct node
{
char* data;
struct node* left;
struct node* right;
};
typedef struct node Node;
int count;
void initnode(Node* root)
{
root->right = NULL;
root->left = NULL;
}
void addtree(Node* root, char* input)
{
char res = strcmp(input, root->data);
printf("\nres %d\n", res);
if(res < 0)
{
if(root->left == NULL)
{
Node *leaf = (Node *)malloc(sizeof(Node));
initnode(leaf);
root->left = leaf;
//(root)->left->data = malloc(strlen(input) + 1);
strcpy(leaf->data, input);
}else
{
addtree(root->left, input);
}
return;
}
if(res > 0)
{
if(root->right == NULL)
{
Node *leaf = (Node *)malloc(sizeof(Node));
initnode(leaf);
root->right = leaf;
//(root)->right->data = malloc(strlen(input) + 1);
strcpy(leaf->data, input);
}else
{
addtree(root->right, input);
}
return;
}
}
void printtree(Node *root)
{
if( root->left == NULL ) {
printf("%s\n", root->data);
if(root->right != NULL)
{
printtree( root->right);
}
}else
{
printtree(root->left);
}
}
int main(void) {
Node *root = NULL;
char input[128], initial[128];
int choice;
root = (Node *)malloc(sizeof(Node));
initnode(root);
printf("Please enter the first and root word");
scanf("%s", initial);
strtok(initial, "\n" );
strcpy(root->data, initial);
while(choice != 0)
{
printf("Press 0 to exit\n");
printf("Press 1 to enter new word\n");
printf("Press 2 to print tree\n");
scanf("%d", &choice);
getchar();
if(choice == 1)
{
printf("Please enter a string: ");
fgets(input, sizeof input, stdin);
strtok(input, "\n" );
printf("You entered %s", input);
addtree(root, input);
}else if(choice == 2)
{
printtree(root);
}
}
return 0;
}
Output:
Please enter the first and root wordHello
Press 0 to exit
Press 1 to enter new word
Press 2 to print tree
1
Please enter a string:Hi
You entered Hi
res 1
Press 0 to exit
Press 1 to enter new word
Press 2 to print tree
2
Hi
Hi
Press 0 to exit
Press 1 to enter new word
Press 2 to print tree
Having issues making a Binary Tree that sorts words in C. I feel like my implementation is good, but cannot figure out where or why my words are overwriting each other. It should print Hello Hi and other words, but it just prints the most recently entered word. Any suggestions would be appreciated. I do not think it is my addtree function as the words are added, but maybe its that way I am passing 'root'?