C++实现表达式树
代碼如下:
#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; }結果如下:
總結
- 上一篇: 胡柚的功效与作用、禁忌和食用方法
- 下一篇: C++实现dijkstra单源最短路径