#include<iostream> #include<stack> #include<string> using namespace std; typedef struct no { char data; struct no *lchild,*rchild; }*node; void create(node &root,string sa,string sb)///根据中/后序遍历,建树 { if(sa.length() == 0) return ; root = new no(); root->data = sb[sb.length()-1]; root->lchild = root->rchild = NULL; int len = sa.length(); string inl,inr,pol,por; for(int i = 0;i < len;i ++){ if(sa[i] == root->data){ inr = sa.substr(i+1,len-i-1); inl = sa.substr(0,i); break; } } //cout<<inl<<"----"<<inr<<endl; int l1 = inl.length(),l2 = inr.length(); pol = sb.substr(0,l1);///小心啊,多+1,少+1,导致半个小时找bug por = sb.substr(l1,l2); //cout<<pol<<"******"<<por<<endl; create(root->lchild,inl,pol);///递归建树 create(root->rchild,inr,por); } void pre(node & sa){ if(sa != NULL){ cout<<sa->data; pre(sa->lchild); pre(sa->rchild); } } int main() { string in,post; cout<<"输入中缀表达式:"<<endl; cin>>in; cout<<"输入后缀表达式:"<<endl; cin>>post; node head; head=new no(); create(head,in,post); cout<<"前缀表达式为:"<<endl; pre(head); cout<<endl; }
时间: 2024-10-16 11:53:43