I'm trying to create a binary tree like this: link
The input will be entered by the user as prefix and read as a string, then put in a binary tree.
This is what I have so far:
struct node{
char val;
struct node *left;
struct node *right;
};
typedef struct node root;
typedef root *tree;
In main:
void main(){
int i;
tree tr;
char* s;
s=input(); //input function
tr=create_empty_tree();
for(i=0;s[i]!='\0';i++){
tr=add_root(s[i],ab);
}
convert_infix(tr);
}
and this is the part I've been struggling with for days; I can't seem to build the tree correctly. This is what I have so far:
tree add_root(char val, tree tr){
if ( tr == NULL ){
tr= create_root(val);
}
else{
if(val=="*" || val=="+" || val=="-" || val=="/"){
tr->left= add_root(val, tr->left);
}
else{
if(tr->left == NULL){
tr->left= add_root(val, tr->left);
}
else{
tr->right= add_root(val, tr->right);
}
}
}
return tr;
}
I looked this up online and I know that my function is wrong, I tried doing this:
Insert new nodes, each time moving to the left until an operand has been inserted.
Backtrack to the last operator, and put the next node to its right.
Continue in the same pattern.
but I don't know how to backtrack. I've been at this for days and I'm going crazy; I'm just a beginner in programming so please don't judge.
Simple sample(Error checking has been simplified)
you have a problem here, a
char
is not a stringchar*
so you can't do something like make a comparison between achar
and achar *
......''
is used for char when""
is used for c string i.echar *
so replace this:by the following code