//目录

二叉树遍历,先序序列+中序序列=后序序列,Poj(2255)

这里我参考了JHF大神的写法啦,直接把输出写在了建树的过程中了。

思路:

先根据先序序列找到根节点,在找该节点在中序序列中的位置,这样,左右子树有分开了。
这里的细节值得注意一下,不然很容易建树出错。(要减去inl,inl之前的已经成为别的子树的一部分了)

左树:make(prel+1,prel+1+pos-inl,inl,pos);

右树:make(prel+1+pos-inl,prer,pos+1,inr);

 

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

const int maxn = 50;

char pre[maxn],in[maxn],post[maxn];
int len;

///找根节点在中序中的位置
int find(int l,int r,char ch)
{
    for(int i=l;i<r;i++)
        if(in[i] == ch)
            return i;
    return -1;
}

///当前树在先序序列中的左端点,右端点,
///中序中的左端点,右端点
void make(int prel,int prer,int inl,int inr)
{
    if(prel>=prer)
        return ;
    if(prel==prer-1)
    {
        printf("%c",pre[prel]);
        return ;
    }

    int pos = find(inl,inr,pre[prel]);

    make(prel+1,prel+pos-inl+1,inl,pos);
    make(prel+pos-inl+1,prer,pos+1,inr);
    printf("%c",pre[prel]);
}

int main()
{
    while(scanf("%s%s",pre,in)!=EOF)
    {
        len=strlen(pre);
        make(0,len,0,len);
        printf("\n");
    }
    return 0;
}

 

posted @ 2016-06-23 10:31  小草的大树梦  阅读(261)  评论(0编辑  收藏  举报