dfs(0,7,0,7)
中序: FDBEG A CH
后序: FDGEB HC A
p=5
dfs(0,4,6,7)
dfs(0,4,5,6)
dfs(zs,p-1,hs,hs+(p-zs)-1);
dfs(p+1,ze,hs+(p-zs),he-1);
#include<iostream> #include<cstring> #include<cstdio> using namespace std; char Z[9],H[9]; //分别表示中序 和 后序 void dfs(int zs,int ze,int hs,int he){ //4个参数zs ze hs he分别表示子树的中序和后序在原序列中的开始下标和结束下标 if(zs<ze){ //递归 int p=zs; while(p<=ze && Z[p]!=H[he]) p++; cout<<H[he]; dfs(zs,p-1,hs,hs+(p-zs)-1); dfs(p+1,ze,hs+(p-zs),he-1); return; } if(zs==ze) cout<<Z[zs]; //结束条件,表示叶子节点 return; //递归停止 } int main(){ cin>>Z>>H; dfs(0,strlen(Z)-1,0,strlen(H)-1); // 最开始是0~n-1 cout<<endl; return 0; }