1. 程式人生 > >求二叉樹的層次遍歷(先加中序還原 + 層次遍歷)

求二叉樹的層次遍歷(先加中序還原 + 層次遍歷)

求二叉樹的層次遍歷

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;
}