求二叉樹的層次遍歷 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic PRoblem Description
已知一顆二叉樹的前序遍歷和中序遍歷,求二叉樹的層次遍歷。 Input
輸入數(shù)據(jù)有多組,輸入T,代表有T組測試數(shù)據(jù)。每組數(shù)據(jù)有兩個(gè)長度小于50的字符串,第一個(gè)字符串為前序遍歷,第二個(gè)為中序遍歷。 Output
每組輸出這顆二叉樹的層次遍歷。 Example Input
2 abc bac abdec dbeac Example Output
abc abcde Hint
Author
fmh
這個(gè)題是根據(jù)前序和中序重建二叉樹,然后在求層序遍歷。
#include<stdio.h>#include<stdlib.h>#include<string.h>char a[55];char b[55];struct node{ int data; struct node *l, *r;};struct node *creat(int n, char *a, char *b)//重建二叉樹{ int i; struct node *root; if(n == 0) return NULL; root = (struct node *) malloc(sizeof(struct node)); root -> data = a[0]; for(i = 0; i < n; i++) { if(b[i] == a[0]) break; } root -> l = creat(i, a+1, b); root -> r = creat(n-1-i, a+i+1, b+i+1); return root;//重建完成};void cengxu(struct node *root)//求層序遍歷{ int in = 0, out = 0; struct node *p[100];//用于儲(chǔ)存每一層的數(shù)據(jù) p[in++] = root; while(in > out) { if(p[out]) { printf("%c", p[out] -> data); p[in++] = p[out] -> l; p[in++] = p[out] -> r; } out++; }}int main(){ int t, n; scanf("%d", &t); while(t--) { scanf("%s%s",a , b); n = strlen(a); struct node *root; root = creat(n, a, b); cengxu(root); printf("/n"); } return 0;}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注