求二叉树的层次遍历
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Example Input
2 abc bac abdec dbeac
Example Output
abc abcde #include<stdio.h> #include<stdlib.h> #include<string.h> struct node { char date; struct node *lchild, *rchild; }; struct node *creat(char *a, char *b, int n) { char *p; struct node *ptr; int k = 0; if(n <= 0) { ptr = NULL; } else { ptr = (struct node *)malloc(sizeof(struct node)); ptr -> date = a[0]; for(p = b; *p != '\0'; p++) { if(*p == a[0]) { break; } } k = p - b; ptr -> lchild = creat(a + 1, b, k); ptr -> rchild = creat(a + k + 1, b + k + 1, n - k - 1); } return ptr; } void put(struct node *T) { struct node *que[100]; int i, j; i = j = 0; que[j++] = T; while(i < j) { if(que[i] -> lchild != NULL)que[j++] = que[i] -> lchild; if(que[i] -> rchild != NULL)que[j++] = que[i] -> rchild; printf("%c", que[i] -> date); i++; } } int main() { int t; char a[100], b[100]; int n; struct node *T; scanf("%d", &t); while(t--) { T = NULL; scanf("%s%s", a, b); n = strlen(a); T = creat(a, b, n); put(T); printf("\n"); } return 0; }