F-Data structure experiment seeking binary tree post-order traversal and hierarchical traversal

Description

Given the pre-order traversal and middle-order traversal of a binary tree, find the post-order traversal and layer-order traversal of the binary tree.
Input

There are multiple sets of input data. The first line is an integer t (t<1000), which means there are t sets of test data. Each group includes two strings with a length less than 50. The first string represents the pre-order traversal sequence of the binary tree, and the second string represents the middle-order traversal sequence of the binary tree.
Output

The first row of each group outputs the post-order traversal sequence of the binary tree, and the second row outputs the hierarchical traversal sequence of the binary tree.
Sample

Input

2
abdegcf
dbgeafc
xnliu
lnixu
Output

dgebfca
abcdefg
linux
xnuli

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char a[1005],b[1005];
struct node
{
    
    
    int date;
    struct node *l,*r;
};
struct node *creat(int len,char a[51],char b[51])
{
    
    int i;
    struct node *root;
    if(len==0)
    {
    
    
        return NULL;

    }
    root=(struct node*)malloc(sizeof(struct node));
    root->date=a[0];
    for(i=0;i<len;i++)
    {
    
    
        if(b[i]==a[0])
            break;
    }
    root->l=creat(i,a+1,b);
    root->r=creat(len-i-1,a+i+1,b+i+1);
    return root;
};
void cengxu(struct node * root)
{
    
    
    struct node * temp[100];                                //关键中间变量存放每一层的数据
    int in = 0, out = 0;
    temp[in++] = root;                                      //每次把这一层存入,然后输出的时候就把他的左右节点存入
    while(in > out)                                         //例如一颗完全二叉树abcdefg  输出a的时候把bc放入,输出b的时候把b
    {
    
                                                           //的孩子放入也就是de,再输出c并且放入孩子fg,依次这样,达到层序的要求
        if(temp[out])
        {
    
    
            printf("%c",temp[out]->date);
            temp[in++] = temp[out]->l;
            temp[in++] = temp[out]->r;
        }
        out++;
    }
}
void houxu(struct node *root)
{
    
    
    if(root)
    {
    
    
        houxu(root->l);
        houxu(root->r);
        printf("%c",root->date);
    }
}
int main()
{
    
    int n,len;
scanf("%d",&n);
struct node *root;
while(n--)
{
    
    
    scanf("%s",a);
    scanf("%s",b);
    len=strlen(a);
    root=creat(len,a,b);
    houxu(root);
    printf("\n");
    cengxu(root);
    printf("\n");
}
    return 0;
}

Guess you like

Origin blog.csdn.net/a675891/article/details/103963423