2137數據結構實驗之求二叉樹後序遍歷和層次遍歷

數據結構實驗之求二叉樹後序遍歷和層次遍歷

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

 已知一棵二叉樹的前序遍歷和中序遍歷,求二叉樹的後序遍歷和層序遍歷。

Input

 輸入數據有多組,第一行是一個整數t (t<1000),代表有t組測試數據。每組包括兩個長度小於50 的字符串,第一個字符串表示二叉樹的先序遍歷序列,第二個字符串表示二叉樹的中序遍歷序列。

Output

每組第一行輸出二叉樹的後序遍歷序列,第二行輸出二叉樹的層次遍歷序列。

Sample Input

2
abdegcf
dbgeafc
xnliu
lnixu

Sample Output

dgebfca
abcdefg
linux
xnuli

Hint

Source

ma6174


注在VJ上提交這個代碼記得選擇 C++提交,要不然會報錯。弱弱的我也不清楚怎麼回事。。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
    char data;
    struct node *left;
    struct node *right;
}tree;
char str1[54],str2[54];
tree *root,*link[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->data=str1[0];
    for(i=0;i<len;i++)
    {
        if(str2[i]==root->data)
            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)
    {
        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]->data);
            }
            i++;
        }
    }
}
void post(tree *root)//後序遍歷序列
{
    if (root)
    {
        post(root->left);
        post(root->right);
        printf("%c",root->data);
    }

}


int main()
{
    int t,len;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s %s",str1,str2);
        len=strlen(str1);
        root=get_build(len,str1,str2);
        post(root);
        printf("\n");
        ans(root);
        printf("\n");
    }

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章