数据结构之已知二叉树前中序列求后序

来源:互联网 发布:战网客户端 mac 编辑:程序博客网 时间:2024/05/21 18:16

数据结构实验之求二叉树后序遍历和层次遍历

Time Limit: 1000MS Memory limit: 65536K

题目描述

 已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

输入

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

输出

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

示例输入

2abdegcfdbgeafcxnliulnixu

示例输出

dgebfcaabcdefglinuxxnuli

提示

 

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<malloc.h>char pre[1000],mid[1000];//前序和后序struct node{    char data;    struct node *lc,*rc;};//已知前中序列求后序方法一/*struct node *check(char pre[],char mid[],int len){    struct node *root;    if(len<=0)    {        return NULL;    }    char *p;    int k;    root=(struct node *)malloc(sizeof(struct node));    root->data=pre[0];    for(p=mid;p!=NULL;p++)//从中序中查找与前序中树根节点相同的值    {        if(*p==*pre)            break;    }    k=p-mid;    //通过递归调用查找子数的树根    root->lc=check(pre+1,mid,k);//无限递归调用左子树    root->rc=check(pre+k+1,p+1,len-k-1);//无限递归调用右子树    return root;}*///已知前中序列求后序方法二struct node *check(char pre[],char mid[],int len){    struct node *root;    if(len<=0)    {        return NULL;    }    char *p;    int k;    root=(struct node *)malloc(sizeof(struct node));    root->data=pre[0];    int i;    for(i=0;i<len;i++)//从中序中查找与前序中树根节点相同的值    {        if(mid[i]==pre[0])            break;    }    //通过递归调用查找子数的树根    root->lc=check(pre+1,mid,i);//无限递归调用左子树    root->rc=check(pre+i+1,mid+i+1,len-i-1);//无限递归调用右子树    return root;}//后序输出void lastput(struct node *root){    if(root!=NULL)    {        lastput(root->lc);        lastput(root->rc);        printf("%c",root->data);    }}//层序输出void septum(struct node *root){    int yes,no;    yes=no=0;    struct node *q[1000];    q[yes++]=root;    while(yes>no)    {        if(q[no]!=NULL)        {            printf("%c",q[no]->data);            q[yes++]=q[no]->lc;            q[yes++]=q[no]->rc;        }        no++;    }}int main(){    int n;    scanf("%d",&n);    while(n--)    {        struct node *root1;        scanf("%s %s",&pre,&mid);        int len;        len=strlen(pre);        root1=check(pre,mid,len);        lastput(root1);        printf("\n");        septum(root1);        printf("\n");    }    return 0;}


0 0
原创粉丝点击