题意是已知中序遍历和后序遍历,求层序遍历
思路是对于每一棵子树其根,总是在后续遍历的最后,可以递归的求解
一开始没考虑到是BT而不是BST ,左子树并不一定小于右子树,wa了一次
后来deep+1改成左边2*deep,右边2*deep+1,ac
#include<stdio.h>
struct list{
int value;
int deep;
} preorder[30];
int pp;
int compare(struct list a,struct list b){
if(a.deep == b.deep)
return a.value - b.value;
else return a.deep - b.deep;
}
void PostToPre(int postorder[],int inorder[],int n,int deep){
if(n){
int povit;
povit = postorder[n-1];
preorder[pp++].value = povit;
preorder[pp-1].deep = deep;
int i;
for(i = 0;i<n;i++)
if(inorder[i] == povit)
break;
PostToPre(postorder,inorder,i,2*deep+2);
PostToPre(postorder+i,inorder+i+1,n-i-1,2*deep+3);
}
}
int main(){
int postorder[30],inorder[30];
int n,i,j;
struct list tmp;
scanf("%d",&n);
for(i = 0;i<n;i++)
scanf("%d",&postorder[i]);
for(i = 0;i<n;i++)
scanf("%d",&inorder[i]);
PostToPre(postorder,inorder,n,0);
for(i = 0;i<n;i++)
for(j = i+1;j<n;j++){
if(compare(preorder[j],preorder[i])<0){
tmp = preorder[i];
preorder[i] = preorder[j];
preorder[j] = tmp;
}
}
for(i = 0;i<n;i++){
printf("%d",preorder[i].value);
if(i == n-1)
printf("\n");
else printf(" ");
}
return 0;
}