https://vjudge.net/problem/HDU-1710
#include<iostream>
#include<cstdio>
using namespace std;
int t1[1001],t2[1001];
void sousuo(int a,int b,int n,int flag)//t1[a] 是根节点 t2[b] 是根节点的树最左边的数字 n 是以根节点的树所有的节点数
{
cout << endl;
cout << "a = " << a << " b = " << b << " n = " << n <<endl;
if(n==1)//如果存在左子树或右子树就直接输出
{
cout << "t1[a = " << a << "] = ";
printf("-------------------%d \n",t1[a]);
cout << endl;
return ;
}
else if(n<=0){//如果不存在左子树或右子树就返回上一层
cout << "n <= 0 return " << endl;
cout << endl;
return ;
}
int i;//继续罚分为左子树和右子树
cout << "a = " << a << "$$$for(i=0;t1[a]!=t2[b+i];i++)" << endl;
cout << "t1[" << a << "] = " << t1[a] << " t2[" << b << "] = " << t2[b] << endl;
for(i=0;t1[a]!=t2[b+i];i++) ;//找到罚分点也就是根节点
cout << "left : a+1 = "<<a + 1<<" ,b = "<<b<<" ,i = "<<i<<",0 " << endl;
sousuo(a+1,b,i,0);//左子树的遍历 因为最左边都是相同的,所以还是传b 总数 = 上个根节点的左子树
cout << "a = " << a << "for(i=0;t1[a]!=t2[b+i];i++)" << endl;
cout << "right : a+i+1 = "<<a+i+1<<" ,b+i+1 = "<<b+i+1<<" ,n-i-1 = "<<n-i-1<<" ,0 i = "<< i << endl;
cout << "t1[" << a+i+1 << "] = " << t1[a+i+1] << " t2[" << b+i+1 << "] = " << t2[b+i+1] << endl;
sousuo(a+i+1,b+i+1,n-i-1,0);//右子树的遍历 a+i到了最左边 a+i+1 到了 t1[a] 的右子树的第一个, b+i 到了根节点,+1 到了右子树最左边 n - (左子树) - (根节点) = n(右子树)
if(flag==1){//最原始的跟节点
printf("*****************%d",t1[a]);
cout << endl;
}
else{//一般的根节点
cout << " t1[a = " << a << "] = ";
printf("~~~~~~~~~~~~~~~~~%d \n",t1[a]);
cout << endl;
}
cout << endl;
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF)
{
cout << endl;
cout <<"OO 1 2 3 4 5 6 7 8 9 10"<<endl;
cout <<"T1 ";
for(i=1;i<=n;i++)
scanf("%d",&t1[i]);//t1中存的是前序
cout <<"T2 ";
for(i=1;i<=n;i++)//t2中存的中序
scanf("%d",&t2[i]);
sousuo(1,1,n,1);
printf("\n");
}
return 0;
}
9
OO 1 2 3 4 5 6 7 8 9 10
T1 1 2 4 7 3 5 8 9 6
T2 4 7 2 1 8 5 9 3 6
a = 1 b = 1 n = 9
a = 1$$$for(i=0;t1[a]!=t2[b+i];i++)
left : a+1,b,i,0 : 2 1 3
a = 2 b = 1 n = 3
a = 2$$$for(i=0;t1[a]!=t2[b+i];i++)
left : a+1,b,i,0 : 3 1 2
a = 3 b = 1 n = 2
a = 3$$$for(i=0;t1[a]!=t2[b+i];i++)
left : a+1,b,i,0 : 4 1 0
a = 4 b = 1 n = 0
n <= 0 return
a = 3for(i=0;t1[a]!=t2[b+i];i++)
right : a+i+1,b+i+1,n-i-1,0 : 4 2 1
a = 4 b = 2 n = 1
t1[a = 4] = -------------------7
t1[a = 3] = ~~~~~~~~~~~~~~~~~4
a = 2for(i=0;t1[a]!=t2[b+i];i++)
right : a+i+1,b+i+1,n-i-1,0 : 5 4 0
a = 5 b = 4 n = 0
n <= 0 return
t1[a = 2] = ~~~~~~~~~~~~~~~~~2
a = 1for(i=0;t1[a]!=t2[b+i];i++)
right : a+i+1,b+i+1,n-i-1,0 : 5 5 5
a = 5 b = 5 n = 5
a = 5$$$for(i=0;t1[a]!=t2[b+i];i++)
left : a+1,b,i,0 : 6 5 3
a = 6 b = 5 n = 3
a = 6$$$for(i=0;t1[a]!=t2[b+i];i++)
left : a+1,b,i,0 : 7 5 1
a = 7 b = 5 n = 1
t1[a = 7] = -------------------8
a = 6for(i=0;t1[a]!=t2[b+i];i++)
right : a+i+1,b+i+1,n-i-1,0 : 8 7 1
a = 8 b = 7 n = 1
t1[a = 8] = -------------------9
t1[a = 6] = ~~~~~~~~~~~~~~~~~5
a = 5for(i=0;t1[a]!=t2[b+i];i++)
right : a+i+1,b+i+1,n-i-1,0 : 9 9 1
a = 9 b = 9 n = 1
t1[a = 9] = -------------------6
t1[a = 5] = ~~~~~~~~~~~~~~~~~3
*****************1