感觉所有case都过了,但就是WA。到时再看看。
题目已经说了第一行n,(1<=n<=1000), 所以不可能像他书上说的出现“二叉树根结点指针为NULL”的情况吧。
#include<stdio.h>
const int MAXN = 15;
int preorder[MAXN];
int inorder[MAXN];
struct node
{
int val;
node *left;
node *right;
};
int fg = 1;
node * create(int pre_begin,int in_begin, int in_end)
{
if(fg == 0)
return NULL;
node *pa = new node;
pa->left = NULL;
pa->right = NULL;
pa->val= preorder[pre_begin];
int i,index=-1;
for(i=in_begin;i<=in_end;i++){
if(preorder[pre_begin]==inorder[i]){
index = i;
break;
}
}
if(index == -1)
fg = 0;
if(index == in_begin)
pa->left = NULL;
else {
pa->left = create(pre_begin+1, in_begin, index-1);
}
if(index == in_end)
pa->right = NULL;
else {
pa->right = create(pre_begin+index-in_begin+1, index+1, in_end);
}
return pa;
}
void print(node *root)
{
if(root != NULL){
if(root->left!=NULL)
print(root->left);
if(root->right!=NULL)
print(root->right);
printf("%d ",root->val);
}
}
int main()
{
int n,i,j;
struct node* root;
root= new node;
freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
for(i=0;i<n;i++)
scanf("%d",&preorder[i]);
for(j=0;j<n;j++)
scanf("%d",&inorder[j]);
root = create(0, 0, n-1);
if(fg == 1){
print(root);
} else {
printf("No");
}
printf("\n");
}
return 0;
}