Im trying to call the function buildExpressionTree with the string "(4+5)" I tried to debug and found out that the tree is created successfully but when returned back to main, "tr" is empty and contains garbage. why does it fail to return the Tree? please help, thank you!
int main(){
char str[SIZE];
Tree tr;
double res;
BOOL expressionOK;
printf("Please enter the expression: ");
gets(str);
expressionOK = buildExpressionTree(str, &tr);
freeTree(tr);
return 0;
}
this is "buildExpressionTree" Function:
BOOL buildExpressionTree(char * str, Tree * tr){
BOOL valid = isvalidString(str);
if (valid){
tr = (Tree *)malloc(sizeof(Tree));
tr->root = buildTree(str, strlen(str));
}
else{
tr = NULL;
}
return valid;
}
and this is the recursive function creating the tree:
TreeNode * buildTree(char * str, int strLength){
int mainOpPlace;
TreeNode * resNode;
//if empty tree
if (strLength < 0){
return NULL;
}
else{
//find the main operator of the current string
mainOpPlace = findMainOperator(str, strLength);
//creating the tree Node
resNode = (TreeNode *)malloc(sizeof(TreeNode));
resNode->data = str[mainOpPlace];
resNode->left = (buildTree(str + 1, mainOpPlace - 1));
resNode->right = (buildTree(str + mainOpPlace + 1, (strLength - mainOpPlace - 2)));
return resNode;
}
}