题目要求
输入一个中缀表达式,构造表达式树,以文本方式输出树结构。
输入:例如,输入a+b+c*(d+e)
输出:以缩进表示二叉树的层次,左——根、右——叶、上——右子树、下——左子树
代码如下
#include<iostream>
#include<string>
#include<fstream>
#include<stack>
#include <iomanip>
#include <cstdio>
using namespace std;
int m[128];
template<class T>
struct TreeNode {
T val;
TreeNode* left;
TreeNode* right;
TreeNode(T x) {
val=x;
left = nullptr;
right=nullptr;
}
TreeNode() {
val = 0;
left = nullptr;
right = nullptr;
}
};
//中缀表达式转后缀表达式
string transform(string zhongzhui) {
char c;
string tmp, houzhui;
stack<char>st;
int len = zhongzhui.length();
for (int i = 0; i < len; i++) {
c = zhongzhui[i];
if (c == '(')
st.push(c);
else if (c == ')') {
while (st.top() != '(') {
tmp = st.top();
houzhui.append(tmp);
st.pop();
}
st.pop();
}
else if (st.empty() && m[c] >= 1)
st.push(c);
else if (m[c] >= 1) {
while (!st.empty() && m[st.top()] >= m[c]) {
tmp = st.top();
houzhui.append(tmp);
st.pop();
}
st.push(c);
}
else {
tmp = c;
houzhui.append(tmp);
}
}
while (!st.empty()) {
tmp = st.top();
houzhui.append(tmp);
st.pop();
}
return houzhui;
}
TreeNode<char>* buildTree(string s)
{
char ch;
TreeNode<char>*p=new TreeNode<char>;
if (s.length() == 0) {
cout << "此树为空" << endl;
return p;
}
stack<TreeNode<char>*>st;
for (int i = 0; i < s.length(); i++) {
ch = s[i];
if (m[ch] >= 1) {
p = new TreeNode<char>;
TreeNode<char> *tmp = st.top();
p->right = tmp;
st.pop();
tmp = st.top();
p->left = tmp;
st.pop();
p->val =ch;
st.push(p);
}
else {
p = new TreeNode<char>;
p->val = ch;
st.push(p);
}
}
return p;
}
// 递归打印输出
void show(TreeNode<char> *x, int d) {
if (x != NULL) {
show(x->right, d + 1);
cout << setw(5 * d) << " "<< x->val << endl;
show(x->left, d + 1);
}
}
int main() {
m['+'] = m['-'] = 1;
m['*'] = m['/'] = 2;
// 输入
ifstream infile("input.txt");
string s;
getline(infile, s);
s=transform(s);
//输出
show(buildTree(s), 0);
return 0;
}