看算法入门经典的二叉树重建,觉得递归真是神级技能,看了好久还是想不出该如何写出这个递归,似懂非懂,囫囵吞枣,暂且放博客记下。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
void build(int n,char *s1,char*s2,char*s)
{
if(n <= 0) return ;
int p = strchr(s2,s1[0]) - s2; //strchr返回一个指针,指针相减得到所找字符的位置 ,找不到的话返回NULL。
build(p,s1+1,s2,s); //递归构造左子树的后续遍历
build(n-p-1,s1+p+1,s2+p+1,s+p); //递归构造右子树的后续遍历
s[n-1]=s1[0]; //把根结点添加到最后
}
int main()
{
char a[100],b[100];
while(cin>>a>>b)
{
char *a1 = strchr(a,'B');
char *a2 = strchr(a,'C');
int p = a2-a1;
cout<<p<<"*************"<<endl;
char s[100];
int t = strlen(a);
build(t,a,b,s);
s[t]='\0';
cout<<s<<endl;
}
return 0;
}