码迷,mamicode.com
首页 > 其他好文 > 详细

[复试机试]已知中序遍历和后序遍历,求前序遍历

时间:2017-02-25 23:56:04      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:oid   导致   bsp   前缀表达式   typedef   end   ack   create   stream   

#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;
}

 

[复试机试]已知中序遍历和后序遍历,求前序遍历

标签:oid   导致   bsp   前缀表达式   typedef   end   ack   create   stream   

原文地址:http://www.cnblogs.com/ACMERY/p/6443163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!