#include <string>
#include <math.h>
using namespace std;
int maxk;
string sa, sb;
char dst[1000];
int index[30];
void init()
{
//initiation
maxk = 0;
memset(dst, ‘^‘, sizeof(dst));
memset(index, 0, sizeof(index));
cout << "The PostOrder Of the tree:/n";
}
//求后序遍历的算法
void cal_tree(string sa, string sb)
{
if(sb.length() == 0) return;
if(sb.length() == 1) {cout << sb;return;}
char x = sa[0];
int mid = sb.find(x);
string c = sb.substr(0, mid);
string d = sb.substr(mid+1);
cal_tree(sa.substr(1, c.length()), c);
cal_tree(sa.substr(1+c.length()), d);
cout << x;
}
//求层次遍历的算法
void cal_BFStree(string sa, string sb, char * dst, int k, int pos)
{
if(k>maxk) maxk = k;
if(sb.length() == 0) return;
if(sb.length() == 1)
{
dst[(int)pow(2, k-1)-1+pos-1] = sb[0];
return;
}
char x = sa[0];
dst[(int)pow(2, k-1)-1+pos-1] = x;
int mid = sb.find(x);
string c = sb.substr(0, mid);
string d = sb.substr(mid+1);
cal_BFStree(sa.substr(1, c.length()), c, dst, k+1, 2*pos-1);
cal_BFStree(sa.substr(1+c.length()), d, dst, k+1, 2*pos);
}
void work()
{
cal_tree(sa, sb);
cal_BFStree(sa, sb, dst, 1, 1);
}
void output()
{
cout << endl;
int i, k=0;
cout << "The Tree in the RAM is like this:-) /n";
for(i=0; i<pow(2, sa.length()); i++)
{
cout << dst[i];
if(i==pow(2, k)-1) k++;
if(k>maxk) break;
}
cout << endl;
}
int main()
{
while(cin >> sa >> sb)
{
init();
work();
output();
}
return 0;
}
Sample Input
Sample Output
DBACEGF ABCDEFG
The PostOrder Of the tree:
ACBFGED
The Tree in the RAM is like this:-)
DBEAC^G^^^^^^F^^
BCAD CBAD
The PostOrder Of the tree:
CDAB
The Tree in the RAM is like this:-)
BCA^^^D^
DBACEGF ABCDEFG BCAD CBAD