数据结构——根据先序,中序,求后序,层次遍历算法

Description

二叉树的遍历是数据结构中的重要操作。 
已知某个二叉树的先序和中序、或者中序和后序遍历的次序。可以唯一确定该二叉树。 
给出二叉树的先序和中序遍历,确定该二叉树,并输出该二叉树的后序遍历的序列和层次遍历的序列。

Input

两行 
第一行:先序遍历的序列 
第二行:中序遍历的序列

Output

输出该二叉树后序遍历的序列。 
按层次遍历的序列

Sample Input

ABCD
BADC

Sample Output

扫描二维码关注公众号,回复: 1553449 查看本文章
BDCA

ABCD

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
char a[100000],b[100000];  
struct node  
{  
    char data;  
    struct node *l,*r;  
};  
struct node *creat(char *a,char *b,int n)//重建树  
{  
    if(n<=0)  
        return NULL;  
    struct node *root;  
    root=(struct node *)malloc(sizeof(struct node));  
    root->data=*a;  
    int i;  
    for(i=0; i<n; i++)  
    {  
        if(b[i]==*a)  
            break;  
    }  
    root->l=creat(a+1,b,i);//左右分开建树  
    root->r=creat(a+i+1,b+i+1,n-i-1);  
    return root;  
}  
void last(struct node *root)//后序遍历  
{  
    if(root!=NULL)  
    {  
        last(root->l);  
        last(root->r);  
        printf("%c",root->data);  
    }  
}  
void ceng(struct node *root)//层次遍历  
{  
    struct node *z[100000],*p;//用栈进行左右层次遍历  
    int jin,chu;  
    jin=chu=0;  
    z[jin++]=root;  
    while(chu<jin)  
    {  
        p=z[chu++];  
        printf("%c",p->data);  
        if(p->l!=NULL)  
            z[jin++]=p->l;  
        if(p->r!=NULL)  
            z[jin++]=p->r;  
    }  
}  
int main()  
{  
    int t,len;  
    scanf("%d",&t);  
    struct node *root;  
    while(t--)  
    {  
        scanf("%s",a);  
        scanf("%s",b);  
        len=strlen(a);  
        root=creat(a,b,len);  
        last(root);  
        printf("\n");  
        ceng(root);  
        printf("\n");  
    }  
    return 0;  
}

猜你喜欢

转载自blog.csdn.net/zmc1248234377/article/details/79721084