输入一个表达式然后生成树,再输出值

题目:
基于二叉树的表达式求值:输入一个算术表达式(为简单起见,表达式中的数为小于10的正整数),利用二叉树来表示该表达式,首先(1)创建表达式树,然后(2)利用二叉树的遍历操作求表达式的值。
输入样例:(2-3*4)+5# (说明:#为表达式结束符)
输出:-5

#include <iostream>
#include<bits/stdc++.h>
#include <string>
#include <stack>
using namespace std;
double len=0,sum=0,temp=0;
string s,enu="";
stack<double> s1;

struct node
{
    char val;
    node *lef,*rig;
    int ans;
};

//新建结点
node* createNode(char v)
{
    node *n = new node;
    n->val = v;
    n->lef=n->rig = NULL;
    n->ans = 0;
    return n;
}

//判断字符是否为数字
bool isNums(char c)
{
    if(c>='0'&&c<='9')
        return true;
    else
        return false;
}

//把原表达式转换成后缀表达式
string change(string s)
{
    stack<char> s1;
    string s2;
    s2="";
    for(int i=0; i<s.size()-1; i++)
    {
        if(isNums(s[i]))        //如果是数字就连入s2
            s2+=s[i];
        else if(s[i]==')')
        {
            while(!s1.empty())
            {
                if(s1.top()=='(')
                {
                    s1.pop();
                    break;
                }
                s2+=s1.top();
                s1.pop();
            }
        }
        else                    //如果是运算符或左括号就放进堆栈
            s1.push(s[i]);
    }
    while(!s1.empty())          //栈不为空就继续连接
    {
        s2+=s1.top();
        s1.pop();
    }
    return s2;

}

node * buildtree(string s)
{
    stack<node *> s2;
    node *n,*n1,*n2;
    for(int i=0; i<s.size(); i++)
    {
        if(isNums(s[i]))        //如果为数字就直接放入堆栈
        {
            n = createNode(s[i]);
            n->ans = s[i]-'0';
            s2.push(n);
        }
        else
        {
            n = createNode(s[i]);   //如果为运算符就从堆栈提两个数做左右子树的值
            n1 = s2.top();
            s2.pop();
            n2 = s2.top();
            s2.pop();
            //反着放在遍历树的时候得到的表达式就会和输入的一样
            n->lef = n2;
            n->rig = n1;
            s2.push(n);             //再把这个结点放入堆栈
        }
    }
    //循环结束后只剩一个根节点
    n = s2.top();
    s2.pop();
    return n;

}

void solve(node *n){
    if(n){      //如果树不为空则遍历
        solve(n->lef );     //从树叶开始计算
        solve(n->rig );
        char option = n->val ;  //判断字符进行运算
        if (option == '+') n->ans = n->lef->ans + n->rig->ans ;
        if (option == '-') n->ans = n->lef->ans - n->rig->ans ;
        if (option == '*') n->ans = n->lef->ans * n->rig->ans ;
        if (option == '/') n->ans = n->lef->ans / n->rig->ans ;
    }
}

int main()
{
    cin>>s;
    node *n = buildtree(change(s));
    solve(n);
    cout<<n->ans<<endl;

    return 0;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于使用C++实现中缀表达式转换到抽象语法树,并以树状图形式展现结果的问题,我可以给您提供一些思路和建议。 1. 实现中缀表达式转换到抽象语法树的算法 中缀表达式转换到抽象语法树的算法可以使用逆波兰表达式算法,首先将中缀表达式转换为逆波兰表达式,然后利用栈结构进行求,最后生成一棵抽象语法树。在生成抽象语法树时,可以使用节点类来表示每个运算符和操作数。 以下是C++代码示例,用于将中缀表达式转换为抽象语法树并以树状图形式展现。 ```C++ #include <iostream> #include <string> #include <stack> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <fstream> using namespace std; struct TreeNode { char value; TreeNode* left; TreeNode* right; TreeNode(char val): value(val), left(nullptr), right(nullptr){} }; void display(TreeNode* root) { if (!root) return; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { auto node = q.front(); q.pop(); cout << node->value << " "; if (node->left) q.push(node->left); if (node->right) q.push(node->right); } cout << endl; } } bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } int priority(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } vector<string> infixToPostfix(string infix) { vector<string> postfix; stack<char> opStack; istringstream iss(infix); string token; while (iss >> token) { if (isdigit(token[0])) { postfix.push_back(token); } else if (isOperator(token[0])) { while (!opStack.empty() && opStack.top() != '(' && priority(token[0]) <= priority(opStack.top())) { postfix.push_back(string(1, opStack.top())); opStack.pop(); } opStack.push(token[0]); } else if (token[0] == '(') { opStack.push(token[0]); } else if (token[0] == ')') { while (!opStack.empty() && opStack.top() != '(') { postfix.push_back(string(1, opStack.top())); opStack.pop(); } if (!opStack.empty()) opStack.pop(); } } while (!opStack.empty()) { postfix.push_back(string(1, opStack.top())); opStack.pop(); } return postfix; } TreeNode* buildTree(vector<string>& postfix) { stack<TreeNode*> st; for (auto token : postfix) { if (isdigit(token[0])) { st.push(new TreeNode(token[0])); } else if (isOperator(token[0])) { auto right = st.top(); st.pop(); auto left = st.top(); st.pop(); auto node = new TreeNode(token[0]); node->left = left; node->right = right; st.push(node); } } return st.top(); } int main() { string infix = "1 + 2 * 3"; auto postfix = infixToPostfix(infix); auto root = buildTree(postfix); display(root); return 0; } ``` 2. 以树状图形式展现抽象语法树 可以使用Graphviz这样的图形库来实现以树状图形式展现抽象语法树。Graphviz是一个开源的图形可视化软件,可以根据输入的文本描述自动生成图形。在C++程序中,可以使用Graphviz的API来生成抽象语法树的图形,并将其输出到文件中。 以下是C++代码示例,用于将抽象语法树以树状图形式展现。 ```C++ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; struct TreeNode { char value; TreeNode* left; TreeNode* right; TreeNode(char val): value(val), left(nullptr), right(nullptr){} }; void generateDot(TreeNode* root, ofstream& dotFile) { if (!root) return; if (root->left) { dotFile << root->value << " -> " << root->left->value << endl; generateDot(root->left, dotFile); } if (root->right) { dotFile << root->value << " -> " << root->right->value << endl; generateDot(root->right, dotFile); } } void display(TreeNode* root) { ofstream dotFile("tree.dot"); dotFile << "digraph Tree {" << endl; generateDot(root, dotFile); dotFile << "}" << endl; dotFile.close(); system("dot -Tpng -o tree.png tree.dot"); system("open tree.png"); } bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } int priority(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } vector<string> infixToPostfix(string infix) { vector<string> postfix; stack<char> opStack; istringstream iss(infix); string token; while (iss >> token) { if (isdigit(token[0])) { postfix.push_back(token); } else if (isOperator(token[0])) { while (!opStack.empty() && opStack.top() != '(' && priority(token[0]) <= priority(opStack.top())) { postfix.push_back(string(1, opStack.top())); opStack.pop(); } opStack.push(token[0]); } else if (token[0] == '(') { opStack.push(token[0]); } else if (token[0] == ')') { while (!opStack.empty() && opStack.top() != '(') { postfix.push_back(string(1, opStack.top())); opStack.pop(); } if (!opStack.empty()) opStack.pop(); } } while (!opStack.empty()) { postfix.push_back(string(1, opStack.top())); opStack.pop(); } return postfix; } TreeNode* buildTree(vector<string>& postfix) { stack<TreeNode*> st; for (auto token : postfix) { if (isdigit(token[0])) { st.push(new TreeNode(token[0])); } else if (isOperator(token[0])) { auto right = st.top(); st.pop(); auto left = st.top(); st.pop(); auto node = new TreeNode(token[0]); node->left = left; node->right = right; st.push(node); } } return st.top(); } int main() { string infix = "1 + 2 * 3"; auto postfix = infixToPostfix(infix); auto root = buildTree(postfix); display(root); return 0; } ``` 以上代码实现了将中缀表达式"1 + 2 * 3"转换为抽象语法树,并以树状图形式展示。在这个例子中,我们使用了逆波兰表达式算法来生成抽象语法树,使用了Graphviz库来生成树形图形。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值