【二叉樹】前中序求後序,中後序求前序

CN_swords發表於2017-07-02

前中序求後序

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
//#pragma comment(linker, "/STACK:102400000,102400000")

const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF=0x3f3f3f3f;
const int N=100;
const LL mod = 1e9+7;

int Find(char c,char A[],int l,int r){
    for(int i=l; i<=r; i++){
        if(A[i]==c)
            return i;
    }
}

void pronum(char pre[],int pre_l,int pre_r,char in[],int in_l,int in_r){
    if(in_l > in_r)
        return ;
    if(in_l == in_r){
        printf("%c",in[in_l]);
        return ;
    }
    char root=pre[pre_l];
    //printf("%c\n",root);
    int id=Find(root,in,in_l,in_r);
    //printf("%d\n",id);
    pronum(pre,pre_l+1,pre_l+id-in_l,in,in_l,id-1);
    pronum(pre,pre_l+id-in_l+1,pre_r,in,id+1,in_r);
    printf("%c",root);
}


int main()
{
    char pre[N],in[N];
    while(~scanf("%s%s",pre,in))
    {
        int lenp = strlen(pre);
        int leni = strlen(in);
        pronum(pre,0,lenp-1,in,0,leni-1);
        puts("");
    }
}

中後序求前序

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
//#pragma comment(linker, "/STACK:102400000,102400000")

const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF=0x3f3f3f3f;
const int N=100;
const LL mod = 1e9+7;

int Find(char c,char A[],int l,int r){
    for(int i=l; i<=r; i++){
        if(A[i]==c)
            return i;
    }
}

void pronum(char pos[],int pos_l,int pos_r,char in[],int in_l,int in_r){
    if(in_l > in_r)
        return ;
    if(in_l == in_r){
        printf("%c",in[in_l]);
        return ;
    }
    char root=pos[pos_r];
    int id=Find(root,in,in_l,in_r);
    //printf("%c\n",root);
    //printf("%d\n",id);
    printf("%c",root);
    pronum(pos,pos_l,pos_l+id-in_l-1,in,in_l,id-1);
    pronum(pos,pos_l+id-in_l,pos_r-1,in,id+1,in_r);
}


int main()
{
    char pos[N],in[N];
    while(~scanf("%s%s",in,pos))
    {
        int lenp = strlen(pos);
        int leni = strlen(in);
        pronum(pos,0,lenp-1,in,0,leni-1);
        puts("");
    }
}


相關文章