求二叉树的先序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入
输出
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
abdegcf xnliu
仔细想如何寻找左右子数在三种序列中的开始位置地址
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char data;
struct node *left,*right;
};
struct node *creat(int n,char *str1,char *str2)
{
struct node *root;
int i;
if(n==0)
return NULL;
root=(struct node *)malloc(sizeof(struct node ));
root->data=str2[n-1];//找到根节点
printf("%c",root->data);
for(i=0;i<n;i++)//找到str1中的根节点的位置
{
if(str1[i]==str2[n-1])
break;
}
root->left=creat(i,str1,str2);//(左子树的长度,str1中左子树开始位置的地址,str2中左子树开始位置的地址)
root->right=creat(n-i-1,str1+i+1,str2+i);//(右子树的长度,str1中右子树开始位置的地址,str2中右子树开始位置的地址)
return root;
};
int main()
{
int n,len;
char str1[100],str2[100];
scanf("%d",&n);
while(n--)
{
memset(str1,0,sizeof(str1));
memset(str2,0,sizeof(str2));
scanf("%s",str1);
scanf("%s",str2);
len=strlen(str1);
creat(len,str1,str2);
printf("\n");
}
return 0;
}