求二叉树的层次遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample Input
2
abc
bac
abdec
dbeac
Sample Output
abc
abcde
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElementType;
typedef struct TreeNode *BinTree;
struct TreeNode
{
ElementType Data;
BinTree Left;
BinTree Right;
};
char st1[100],st2[100];
struct TreeNode *creat(int n,char *st1,char *st2)
{
struct TreeNode *root;
char *p;
if(n == 0)return NULL;
root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->Data = st1[0];
for(p = st2;p != '\0';p++)
{
if(*p == st1[0])
break;
}
int t;
t = p - st2;
root->Left = creat(t,st1+1,st2);
root->Right = creat(n - t- 1,st1 + t+1,p+1);return root;
}
void cengci(struct TreeNode *root)
{
struct TreeNode *temp[100];
int in = 0,out = 0;
temp[in++] = root;
while(in > out)
{
if(temp[out])
{
printf("%c",temp[out] -> Data);
temp[in++] = temp[out]->Left ;
temp[in++] = temp[out]->Right;
}
out++;
}
}
int main()
{
int t,m;
scanf("%d",&t);
struct TreeNode *root;
root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
while(t--)
{
scanf("%s %s",st1,st2);
m = strlen(st1);
root = creat(m,st1,st2);
cengci(root);
printf("\n");
}
return 0;
}