Alright, I got the code to work, but it only works for inputs that are a single character. How can I get it to work if the input were a word instead of just a letter? I tried using strings but I get segmentations errors.
Code:
#include <stdio.h>
#include <stdlib.h>
struct tnode {
char data;
struct tnode *left;
struct tnode *right;
};
struct tnode *tnode_insert(struct tnode *p, char value);
void print_inorder(struct tnode *p);
int main(void) {
char demo_nr[50], tmp;
struct tnode *root = NULL;
int i=0, k=1, count=0, j;
FILE *fp;
fp=fopen("p2_input.txt", "r");
while(k!=0){
fscanf(fp, "%d %c", &k, &tmp);
demo_nr[count]=tmp;
count++;
}
for(i=0; i<count; i++)
root = tnode_insert(root, demo_nr[i]);
for(j=0; j<count; j++){
printf("%d ", j);
}
printf("\n");
print_inorder(root);
printf("\n");
return 0;
}
struct tnode *tnode_insert(struct tnode *p, char value) {
struct tnode *tmp_one = NULL;
struct tnode *tmp_two = NULL;
if(p == NULL) {
p = (struct tnode *)malloc(sizeof(struct tnode));
p->data = value;
p->left = p->right = NULL;
} else {
tmp_one = p;
while(tmp_one != NULL) {
tmp_two = tmp_one;
if(tmp_one ->data > value)
tmp_one = tmp_one->left;
else
tmp_one = tmp_one->right;
}
if(tmp_two->data > value) {
tmp_two->left = (struct tnode *)malloc(sizeof(struct tnode));
tmp_two = tmp_two->left;
tmp_two->data = value;
tmp_two->left = tmp_two->right = NULL;
} else {
/* insert [new] tnode as left child */
tmp_two->right = (struct tnode *)malloc(sizeof(struct tnode));
tmp_two = tmp_two->right;
tmp_two->data = value;
tmp_two->left = tmp_two->right = NULL;
}
}
return(p);
}
void print_inorder(struct tnode *p){
int j=0;
if(p!=NULL) {
print_inorder(p->left);
printf("%c ", p->data);
print_inorder(p->right);
}
}