求二叉树的层次遍历
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>
struct tree
{
char data;
struct tree *l, *r;
} *root;
struct tree *creat(char a[], char b[], int n);
void at_out(struct tree *root);
int main()
{
int T, L;
scanf("%d", &T);
while(T--)
{
char a[100], b[100];
scanf("%s %s", a, b);
L = strlen(a);
root = creat(a, b, L);
at_out(root);
printf("\n");
}
return 0;
}
struct tree *creat(char a[], char b[], int n) // 根据前序和中序建树
{
if(n <= 0) return NULL;
struct tree *root;
root = (struct tree *)malloc(sizeof(struct tree));
root->data = a[0];
int i;
for(i = 0; i < n; i++)
{
if(b[i] == a[0]) break;
}
root->l = creat(a + 1, b, i);
root->r = creat(a + i + 1, b + i + 1, n - i - 1);
return root;
};
void at_out(struct tree *root)
{
if(root == NULL) return;
int t = 0, i = 0;
struct tree *s[100], *q; //指针类型数组
s[0] = root;
while(t <= i)
{
q = s[t++];
printf("%c", q->data);
if(q->l != NULL)
{
s[++i] = q->l;
}
if(q->r != NULL)
{
s[++i] = q->r;
}
}
}