Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cstdio>
- using namespace std;
- typedef struct Node{
- char ch;
- struct Node *left;
- struct Node *right;
- }Node;
- Node* creattree(const string expr, int index);
- void showPreorder(const Node* root);
- int compute(const Node* root);
- Node* freetree(Node* root);
- int main() {
- freopen("arithmatic.txt", "r", stdin);
- string expr;
- while (cin >> expr) {
- Node *root=NULL;
- root = creattree(expr, 0);
- showPreorder(root);
- cout << endl << compute(root) << endl;
- root = freetree(root);
- }
- return 0;
- }
- Node* creattree(const string expr, int index) {
- if (index >= expr.size())
- return NULL;
- Node *root=NULL;
- root = new Node;
- root->ch = expr[index];
- if (expr[index] == '*' || expr[index] == '+') {
- root->left = creattree(expr, index+1);
- root->right = creattree(expr, index+2);
- } else {
- root->left = NULL;
- root->right = NULL;
- }
- return root;
- }
- void showPreorder(const Node* root) {
- if (root) {
- cout << root->ch;
- showPreorder(root->left);
- showPreorder(root->right);
- }
- }
- Node* freetree(Node* root) {
- if (root) {
- freetree(root->left);
- freetree(root->right);
- free(root);
- root = nullptr;
- }
- return root;
- }
- int compute(const Node* root) {
- if (root->ch == '+') {
- return compute(root->left) + compute(root->right);
- }
- else if (root->ch == '*') {
- return compute(root->left) * compute(root->right);
- }
- else
- return root->ch - '0';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement