### Starter Programmer help please. I'm using RECURSION

The point of my code is to evaluate a mathematical expression that's already formed in a Binary Search Tree. : ((6+5)-3)*(2/1)=?

I've read other forums and they usually use cout, cin and << >> but I'm still in the learning process so this is basically primitive coding.

Anyway, The recursion is already correct (I think). My problem is how to return char* or should I say an element which has 2 or more digits.

 ``12345678910111213141516171819202122232425262728293031323334`` ``````typedef struct cell{ char elem[max]; struct cell *left; struct cell *right; }celltype, *node; node A; char* evaluate(node *A) //passed as evaluation(&A); { char *c=(char*)malloc(sizeof(char),max); char *d=(char*)malloc(sizeof(char),max); strcpy(c,(*A)->elem); d=0; if((*A)->left!=NULL) c=evaluate(&((*A)->left)); if((*A)->right!=NULL) d=evaluate(&((*A)->right)); if(strcmp((*A)->elem,”+”)==0)* c=*c + *d; if(strcmp((*A)->elem,”-“)==0) *c=*d - *c; if(strcmp((*A)->elem,”*”)==0) *c=*c + *d; if(strcmp((*A)->elem,”/”)==0) *c=*d / *c; if(strcmp((*A)->elem,”=”)==0) { (*A)->right=(node)malloc(sizeof(celltype)); (*A)->right->left=NULL; (*A)->right->right=NULL; (*A)->right->elem=*c; } return c; }``````

and the reason that I'm using char is because the operators are also elements in different nodes.

The code above is actually the result when I remembered that you can't return 2-digit char.
The code below is before I remembered that. It works when all results are 1 digit numbers.

 ``1234567891011121314151617181920212223242526272829303132`` ``````typedef struct cell{ char elem; struct cell *left; struct cell *right; }celltype, *node; node A; char evaluate(node *A) //passed as “evaluation(&A);” in main { char c,d; c=(*A)->elem; d=0; if((*A)->left!=NULL) c=evaluate(&((*A)->left)); if((*A)->right!=NULL) d=evaluate(&((*A)->right)); if((*A)->elem==0) c=c+d; if((*A)->elem==0) c=d-c; if((*A)->elem==0) c=c+d; if((*A)->elem==0) c=d/c; if((*A)->elem==0) { (*A)->right=(node)malloc(sizeof(celltype)); (*A)->right->left=NULL; (*A)->right->right=NULL; (*A)->right->elem=c; } return c; }``````

Last edited on
Pass them by reference or their addresses. In this way, you can do something like the following:
 ``1234567891011121314151617181920212223`` ``````#include using namespace std; void change_chars(char&, char&); int main() { char a = 'C'; char b = 'E'; cout << "char a: " << a << "\nchar b:" << b << endl; change_chars(a, b); cout << "--[ After change_chars() ]--" << endl; cout << "char a: " << a << "\nchar b: " << b << endl; cin.get(); return 0; } void change_chars(char& f, char& g) { f = 'A'; g = 'B'; }``````
Topic archived. No new replies allowed.