问题
Can anyone help me out to get postorder traversal as output from gven two traversals:
In-order :A, B, C, D, E, F, G, H, J, K, L, M, P, Q, N.
Pre-order : C, D, E, B, G, H, F, K, L, P, Q, M, N, J, A.
It will be more helpfull if the answere is graphical.
回答1:
Non-Recursive Algorithm ;How to Calculate change Between inorder and preorder ؟؟
#include<stdio.h>
#include<conio.h>
#include <iostream>
using namespace std;
int find(int *p,int s,int f)
{
int k=0;
if (f==0)
return -1;
for(;k<s;k++)
if(*(p+k)==f)
return k;
return -1;
}
int main()
{
int n=15;
int in[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'P', 'Q', 'N'};
int pre[] = {'C', 'D','E','B', 'G', 'H', 'F', 'K', 'L', 'P', 'Q', 'M', 'N', 'J', 'A'};
int i,k,hed,chld,s=0;
int *j=(int *)malloc(sizeof(int)*n);
int *p=(int *)malloc(sizeof(int)*n);
for(k=0;k<n;k++)
j[k]=1;
for(k=0;k<n;k++){
chld=find(in,n,pre[k]);
if(1!=j[chld])
{
int o=chld,t=chld;
while(j[chld]==j[--t])
j[t]=j[chld]*2;
while(j[chld]==j[++o])
j[o]=j[chld]*2+1;
}
else{
int t;
for(t=0;t<n;t++)
if(t<chld)
j[t]++;
else if(t>chld)
j[t]+=2;
}
}
k=1,s=0;
while(1){ hed=find(j,n,k);
if(s>0&&*(p+s-1)==k)
{
for(chld=0;chld<n;chld++)
if(j[chld]==k)
break;
cout<<(char)in[chld]<<" ";
if(k==1)
break;
s--;
hed=-1;
}
if(hed>-1)
{
*(p+s)=k;
s++;
k*=2;
}
else if(k%2==0)
{
k++;
continue;
}
else {
k=k/2;
continue;
}
}
getch();
return 0;
}
来源:https://stackoverflow.com/questions/13056187/get-postorder-bt-traversal-from-given-inorder-and-preorder-traversal