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

来源:互联网 发布:网页链接打开淘宝app 编辑:程序博客网 时间:2024/05/17 23:27

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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

2abdegcfdbgeafcxnliulnixu

示例输出

dgebfcaabcdefglinuxxnuli
 
裸的二叉树,主要是建树与层次遍历
 
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<queue>using namespace std;typedef struct node{    char d;    struct node *l,*r;}tree;char pre[64],mid[64];queue<tree *>q;tree *bu(char *pre,char *mid,int len)//已知前序与中序来建树{    int k;    if(len<=0)        return NULL;    tree*head;    head=(tree *)malloc(sizeof(tree));    head->d=*pre;//插入节点    char *p;    for(p=mid;p!=NULL;p++)//找到当前的根节点        if(*p==*pre)            break;// 在中序遍历的序列中得到与先序相同的节点    k=p-mid;    head->l=bu(pre+1,mid,k);//递归得到左子树,这里虽说是递归但不好理解,左子树的递归为先序和中序同时的进行递归    head->r=bu(pre+k+1,p+1,len-k-1);//得到右子树    return head;}void pos(tree *h){    if(h)    {        pos(h->l);        pos(h->r);        printf("%c",h->d);    }}void lor(tree *h)//直接调用队列,分别按从上到下,从左到右的顺序进队,然后依次遍历次{if(h!=NULL)q.push(h);while(!q.empty()){tree *b;b=q.front();printf("%c",b->d);q.pop();if(b->l){q.push(b->l);}if(b->r)q.push(b->r);}}int main(){    int n,m,i,j,k;    cin>>n;//getchar();    tree *h;    while(n--)    {        cin>>pre;        cin>>mid;        k=strlen(pre);        h=new node;        h=bu(pre,mid,k);        pos(h);        printf("\n");        lor(h);        printf("\n");    }    return 0;}

0 1
原创粉丝点击