zoukankan      html  css  js  c++  java
  • [复试机试]已知中序遍历和后序遍历,求前序遍历

    #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;
    }
  • 相关阅读:
    jenkins更换国内源
    部署jdk和maven
    Prometheus监控Nginx
    Prometheus监控MySQL
    MySql里动态视图的实现
    MySql里split函数的实现
    HTML编码规范
    消弱反驳18招
    Pr2020
    记忆准则
  • 原文地址:https://www.cnblogs.com/ACMERY/p/6443163.html
Copyright © 2011-2022 走看看