样例输入:
DBACEGF ABCDEFG 输出:ACBFGED
BCAD CBAD 输出:CDAB
1 #include "stdafx.h" 2 #include<iostream> 3 #include<string> 4 using namespace std; 5 void show(int n,string lhs,string rhs); 6 int _tmain(int argc, _TCHAR* argv[]) 7 { 8 string s1 = "DBACEGF",s2="ABCDEFG"; 9 int n=s1.size(); 10 show(n,s1,s2); 11 return 0; 12 } 13 14 void show(int n,string lhs,string rhs) 15 { 16 if(n<=0) 17 { 18 return; 19 } 20 char firstWords=lhs[0]; 21 int n1=rhs.find(firstWords);//找到根节点在终须遍历中的位置. 22 int n2=n-n1-1; 23 show(n1,(lhs.substr(1)).substr(0,n1),rhs.substr(0,n1));//递归构造左子树的后序遍历 24 show(n2,lhs.substr(n1+1),rhs.substr(n1+1)); //递归构造右子树的后序遍历 25 cout<<firstWords;//输出根节点. 26 27 }