已知前序遍历和中序遍历求后序遍历和层次遍历

#include <iostream>
#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
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值