代码如下:
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;class Tree
{
private:class Node{public:char val;Node * left;Node *right;Node(char val):val(val),left(nullptr),right(nullptr){}Node():val(0),left(nullptr),right(nullptr){}};Node * root;public:Tree():root(nullptr){}void buildTree(){string str;cin >> str;stack<char>ops;stack<Node*> exps;//这里用栈来处理优先级//遇到运算数,直接压到exps栈中//遇到左括号,直接压入ops栈中//遇到右括号,将栈顶的运算符弹出,并和exps中的两个运算数组成一颗小树,然后把小树的根节点放入exps栈中//当前扫描的运算符优先级大于ops栈栈顶运算符的优先级,直接入ops栈//当前扫描的运算符优先级小于等于ops栈顶运算符的优先级,将栈顶运算符弹出,//并和exps中的两个运算数组成一颗小树,然后把小树的根节点放入exps栈中//直到该运算符优先级大于栈顶运算符优先级或栈为空,然后入栈for (int i = 0; i < str.length(); i++){if (str[i] == '('){ops.push(str[i]);}else if (str[i] == ')'){while (!ops.empty() &&ops.top() != '('){char tmp = ops.top();ops.pop();Node *s2 = exps.top();exps.pop();Node *s1 = exps.top();exps.pop();Node *s = new Node(tmp);s->left = s1;s->right = s2;exps.push(s);}if (!ops.empty()) ops.pop();}else if (!ops.empty() && isOp(str[i]) && isPre(str[i]) > isPre(ops.top())){ops.push(str[i]);}else if (!ops.empty() && isOp(str[i]) && isPre(str[i]) <= isPre(ops.top())){while ( !ops.empty() && isPre(str[i]) <= isPre(ops.top()) ){char tmp = ops.top();ops.pop();Node *s2 = exps.top();exps.pop();Node *s1 = exps.top();exps.pop();Node *s = new Node(tmp);s->left = s1;s->right = s2;exps.push(s);}ops.push(str[i]);}else if (ops.empty() && isOp(str[i])){ops.push(str[i]);}else if (!isOp(str[i])){Node *s = new Node(str[i]);exps.push(s);}}while (!ops.empty()){char tmp = ops.top();ops.pop();Node *s2 = exps.top();exps.pop();Node *s1 = exps.top();exps.pop();Node *s = new Node(tmp);s->left = s1;s->right = s2;exps.push(s);if (ops.size() == 0){root = s;}}}int isPre(char ch)//计算运算符的优先级{if (ch == '*' || ch == '/') return 1;else if (ch == '+' || ch == '-') return 0;else if (ch == '(') return -1;}bool isOp(char ch)//判断是否为运算符{return ch == '*' || ch == '-' || ch == '+' || ch == '/';}int getValue(char ch, int a, int b)//根据运算符进行相应运算{if (ch == '/'){return a / b;}else if (ch == '*'){return a * b;}else if (ch == '+'){return a + b;}else if (ch == '-'){return a - b;}}int getRes()//得到最终的结果{if (root == nullptr){cout << "The tree is empty" << endl;return -1;}return getDfs(root);}int getDfs(Node *s)//遍历这颗树根据运算符计算结果的函数{if (s->left == nullptr && s->right == nullptr){return s->val - '0';}else{int leftVal = getDfs(s->left);int rightVal = getDfs(s->right);return getValue(s->val, leftVal, rightVal);}}void levelOrder()//层次遍历{if (root == nullptr){cout << "The tree is empty" << endl;return;}queue<Node *> q;q.push(root);while (!q.empty()){Node *p = q.front();q.pop();cout << p->val << " ";if (p->left) q.push(p->left);if (p->right)q.push(p->right);}cout << endl;}
};int main()
{Tree t ;t.buildTree();t.levelOrder();Tree t1;t1.buildTree();t1.levelOrder();cout << t1.getRes() << endl;return 0;
}
结果如下: