15.构造二叉树进行四则计算

来源:互联网 发布:淘宝如何举报售假 编辑:程序博客网 时间:2024/06/03 21:09
////////////////////////////////////////#include<cstdio>#include<cstdlib>#include<iostream>#include<queue>#include<stack>#define OK 0#define ERROR 1using namespace std;typedef char Num;typedef char OP;FILE *fp;void InitFile(){fopen_s(&fp, "data.txt", "r");if (!fp) exit(ERROR);return;}typedef bool Status;/////////////////////////////////////////******file input:-+-+1*23/*45678*******///1+2*3-4*5/6+7-8//////////////////////////////////////////二叉树的 链接式存储表示typedef  struct node{Num num;OP op;int flag;struct node *lchild, *rchild;}TreeNode, *tree_ptr;//按照 中序顺序 创建一颗二叉树bool Is_Number(char c){return   c >= '0' && c <= '9';}bool Is_OP(char c){return c == '+' || c == '-' || c == '*' || c == '/';}Status CreateBitTree(tree_ptr &t)//创建一颗二叉树{char c;fscanf_s(fp, "%c", &c);printf("%c ", c);if (Is_Number(c)){t = (tree_ptr)malloc(sizeof(TreeNode));if (!t) exit(ERROR); t->op = '#'; t->flag = 0;t->num = c;t->lchild = t->rchild = NULL;return OK;}else if (Is_OP(c)){t = (tree_ptr)malloc(sizeof(TreeNode));if (!t) exit(ERROR); t->num = '#'; t->flag = 1;t->op = c;CreateBitTree(t->lchild);CreateBitTree(t->rchild);}else { t = NULL;  return OK; }//其实这句话没必要....}//分别 用 递归和非递归 实现二叉树的遍历 Status Inorder(tree_ptr t){if (t){Inorder(t->lchild);if (t->flag) printf("%c ", t->op);else printf("%c ", t->num);Inorder(t->rchild);}return OK;}Status Preorder(tree_ptr t){if (t){if (t->flag) printf("%c ", t->op);else printf("%c ", t->num);Preorder(t->lchild);Preorder(t->rchild);}return OK;}Status Postorder(tree_ptr t){if (t){Postorder(t->lchild);Postorder(t->rchild);if (t->flag) printf("%c ", t->op);else printf("%c ", t->num);}return OK;}char Cal(char a, char s, char b){char q;switch (s){case '+':  q = (a - 48) +(b - 48) + 48;break;case '-':q = (a - 48)- (b - 48) + 48;break;case '*':q = (a - 48) *(b - 48) + 48;break;case '/':q = (a - 48) /(b - 48) + 48;break;}return q;}Status Calculate(tree_ptr t)//对可以计算的符号进行计算{if (t->num=='#'){Calculate(t->lchild);Calculate(t->rchild);t->num = Cal(t->lchild->num, t->op, t->rchild->num);}return OK;}//by zhaoyang 2014.4.19int main(){InitFile();tree_ptr A;printf("创建二叉树的表达式:\n");CreateBitTree(A);printf("\n先序遍历:\n");Preorder(A);printf("\n中序遍历:\n");Inorder(A);printf("\n后序遍历:\n");Postorder(A);printf("\n");Calculate(A);int count = A->num - 48;printf("----------------\ncorrect answer : %d\n", count);printf("\n");return 0;}


0 0
原创粉丝点击