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

来源:互联网 发布:三国数据化 编辑:程序博客网 时间:2024/06/09 17:05

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

题目描述

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

输入

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

输出

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

示例输入

2abdegcfdbgeafcxnliulnixu

示例输出

dgebfcaabcdefglinuxxnuli
#include <iostream>#include<stdio.h>#include<string.h>#include<stdlib.h>#include<math.h>#include<malloc.h>using namespace std;struct node{    char data;    node*left,*right;}*tree;struct node*bulid(int n,char *str1,char *str2){    if(n==0) return NULL;    char *p;    struct node*tree;    tree=(struct node*)malloc(sizeof(struct node));    tree->data=str1[0];    for(p=str2;p!='\0';p++)    {        if(*p==str1[0])            break;    }    int k=p-str2;    tree->left=bulid(k,str1+1,str2);    tree->right=bulid(n-k-1,str1+k+1,p+1);    return tree;};void hou(struct node*tree){    if(tree!=NULL)    {        hou(tree->left);        hou(tree->right);        cout<<tree->data;    }}void ceng(struct node*tree){    int t=0,r=1;    struct node*q[100];    q[0]=tree;    while(t<r)    {        if(q[t])        {            cout<<q[t]->data;            q[r++]=q[t]->left;            q[r++]=q[t]->right;        }        t++;    }}int main(){    int n;    char str1[100],str2[100];    struct node*t;    t=(struct node*)malloc(sizeof(struct node));    cin>>n;    while(n--)    {        cin>>str1>>str2;        int len=strlen(str1);        t=bulid(len,str1,str2);        hou(t);        cout<<"\n";        ceng(t);        cout<<"\n";    }}


0 0
原创粉丝点击