求二叉樹的層次遍歷
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
Hint
Source
fmh
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
char date;
struct node *left;
struct node *right;
}tree;
tree *root,*link[54];
char str1[54],str2[54];
tree *get_build(int len,char *str1,char *str2)//建立二叉樹
{
if(len==0)
return NULL;
int i;
tree *root;
root = (tree *)malloc(sizeof(tree));
root->date=str1[0];//尋找根節點,新的根節點爲前序遍str1的第一個
for(i=0;i<len;i++)//尋找新的根節點在中序遍歷str2中的位置
{
if(str2[i]==root->date)
break;
}
root->left = get_build(i,str1+1,str2);//左子樹的長度,左子樹在前序遍歷中的開始位置,左子樹在中序遍歷中的開始位置
root->right = get_build(len-i-1,str1+i+1,str2+i+1);//右子樹的長度,右子樹在前序遍歷中的位置,右子樹在中序遍歷的位置
return root;
}
void ans(tree *root)//二叉樹的層序遍歷
{
if(root)//判斷root是否爲NULL
{
int i=0,j=0;
link[j++]=root;
while(i<j)
{
if(link[i])
{
link[j++]=link[i]->left;//入隊
link[j++]=link[i]->right;//入隊
printf("%c",link[i]->date);//層序遍歷
}
i++;//出隊
}
}
}
int main()
{
int t,len;
scanf("%d",&t);
while(t--)
{
scanf("%s %s",str1,str2);
len=strlen(str1);
root = get_build(len,str1,str2);//調用建立二叉樹函數
ans(root);//調用二叉樹的層序遍歷函數
printf("\n");
}
return 0;
}