这里我参考了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; }