题目
编写程序:输入表达式,输出相应二叉树的先序遍历结果
输入: a+b*(c-d)-e/f
输出: -+a*b-cd/ef
分析
北理看起来很喜欢考这种题,这个知识点在北理近几年的考研初试试卷中多次出现了。首先要知道的是常见的中缀表达式正是表达式树的中序遍历,相应的:后缀表达式对应表达式树的后序遍历。
但此题也不能直接转化为:通过中序和后序序列求得先序遍历,即使用上一篇博客所记录的方法。因为很多个字符在这个字符串里并不是唯一的。于是尝试使用后缀式直接建立一颗二叉树。
首先一个问题是,如何将中缀式变为后缀式。王道辅导书上的方法为:
- 从左到右扫描中缀表达式。
- 遇到数字时,加入后缀表达式。
- 遇到运算符时:
- 若为
(
:入栈 - 若为
)
:把栈中运算符依次加入到后缀式中,直到遇到(,并删除之。 其他运算符
:栈内的想出来,栈外的想进去(多么现实^ = ^),谁的优先级高就听谁的。
- 若为
运算符 | ( | +,- | *,/ | ) |
---|---|---|---|---|
in Stack Priority(ISP) | 1 | 3 | 5 | 6 |
in Comming Priority(ICP) | 6 | 2 | 4 | 1 |
中缀转后缀代码如下:
#include<iostream>
#include<vector>
#include<stack>
#include<map>
using namespace std;
string inOrder, postOrder;
int main()
{
cin >> inOrder;
stack<char> st;
map<char, int> isp{ {'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6} };
map<char, int> icp{ {'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1} };
for (int i = 0; i < inOrder.length(); i++) {
char t = inOrder[i];
if (t >= '0' && t <= '9' || t >= 'a' && t <= 'z')
postOrder.append(1, t);
else if (t == '(')
st.push(t);
else if (t == ')') {
char c;
while ((c = st.top()) != '(') {
postOrder.append(1, c);
st.pop();
}
st.pop();
}
else {
while (!st.empty() && icp[t] < isp[st.top()]) {
postOrder.append(1, st.top());
st.pop();
}
st.push(t);
}
}
while (!st.empty()) {
postOrder.append(1, st.top());
st.pop();
}
cout << postOrder << endl;
}
后缀式有了,如何建立二叉树呢
如同后缀表达式求值一样,逐次读取后缀表达式的每一个符号
- 如果符号是
操作数
,那么就建立一个单节点树并将一个指向它的指针推入栈中; - 如果符号是
运算符
,则从栈中弹出两棵树T1和T2(先弹出T1),并形成一颗以操作符为根的树,其中T1为右儿子,T2为左儿子;
然后将新的树压入栈中,继续上述过程。
完整代码
#include<iostream>
#include<vector>
#include<stack>
#include<map>
using namespace std;
string inOrder, postOrder;
struct node {
char c;
node *l,*r;
node(char c,node *l=NULL,node *r=NULL):c(c),l(l),r(r){}
};
void preOrder(struct node* p)
{
if (p) {
cout << p->c;
preOrder(p->l);
preOrder(p->r);
}
}
int main()
{
cin >> inOrder;
stack<char> st;
map<char, int> isp{ {'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6} };
map<char, int> icp{ {'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1} };
for (int i = 0; i < inOrder.length(); i++) {
char t = inOrder[i];
if (t >= '0' && t <= '9' || t >= 'a' && t <= 'z')
postOrder.append(1, t);
else if (t == '(')
st.push(t);
else if (t == ')') {
char c;
while ((c = st.top()) != '(') {
postOrder.append(1, c);
st.pop();
}
st.pop();
}
else {
while (!st.empty() && icp[t] < isp[st.top()]) {
postOrder.append(1, st.top());
st.pop();
}
st.push(t);
}
}
while (!st.empty()) {
postOrder.append(1, st.top());
st.pop();
}
// cout << postOrder << endl;
stack<struct node*> s;
for (int i = 0; i < postOrder.length(); i++) {
char t = postOrder[i];
if (t >= 'a' && t <= 'z') {
node* p = new node(t);
s.push(p);
}
else {
node* p = new node(t);
p->r = s.top();
s.pop();
p->l = s.top();
s.pop();
s.push(p);
}
}
preOrder(s.top());
}
好困啊,可还是要追一下决胜法庭哈哈哈