Each element (operands, operators, parenthese) in the prefix expression is seperated by a white space. These are some of the functions needed.
void createExpTree ( BTNode ** root , char * prefix ); void printTree ( BTNode * node ); void printTreePostfix ( BTNode * node ); and this is the structure of the BTnode
typedef struct _btnode{ int item; struct _btnode *left; struct _btnode *right; } BTNode; this is my code for the function createExpTree but I dont understand what is wrong
void createExpTree(BTNode** root,char* prefix) { int j, x; char c; char d[SIZE]; if (*prefix == '\0') return; if (*prefix == ' ') prefix++; c = *prefix; if (c=='*' || c=='/' || c=='+' || c=='-') { // if prefix exp is OPT // create children BTNode* nn = (BTNode*)malloc(sizeof(BTNode)); nn->item = c; nn->left = NULL; nn->right = NULL; *root = nn; prefix++; createExpTree(&((*root)->left), prefix); createExpTree(&((*root)->right), prefix); } else { //if prefix exp is OPERAND j=0; while (c!=' ') { d[j]=c; j++; prefix++; c = *prefix; } d[j]='\0'; x = atoi(d); BTNode* nn = (BTNode*)malloc(sizeof(BTNode)); nn->item = x; nn->left = NULL; nn->right = NULL; *root = nn; prefix++; return; } } these are my codes for printTree and printTreePostfix
void printTree(BTNode *node){ if (node == NULL) { return; } else { printTree(node->left); if(node->item >= 0 || node->item <= INT_MAX) printf("%d ",node->item); else printf("%c ",(char)(node->item)); printTree(node->right); } } void printTreePostfix(BTNode *node){ if (node == NULL) { return; } else { printTreePostfix(node->left); printTreePostfix(node->right); if(node->item >= 0 || node->item <= INT_MAX) printf("%d ",node->item); else printf("%c ",(char)(node->item)); } } The input for this question is something like "+ 99 / + 88 77 - * 66 - 55 44 33", the integers are presumably 2-digit integers. I can't seem to traverse the char array prefix recursively to get the individual pointers in order to create the expression tree.
Does prefix++ even traverse the char array correctly?? is the recursive function call createExpTree(&((*root)->right), prefix); missing anything??
Would appreciate any help!! Thanks!!
**Edited : noticed an error in creating newnode for operand
https://stackoverflow.com/questions/66828074/creating-a-recursive-function-that-creates-a-expression-tree-from-a-prefix-expre March 27, 2021 at 12:43PM
没有评论:
发表评论