您的位置:首页 > 理论基础 > 数据结构算法

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

2018-01-28 22:13 435 查看

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

[align=center]Time Limit: 1000MSMemory Limit: 65536KB[/align][align=center]
[/align]

Problem Description

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

Input

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

Output

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

Example Input

2
abdegcf
dbgeafc
xnliu
lnixu

Example Output

dgebfca
abcdefg
linux
xnuli


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
char data;
struct node *left,*right;
};

struct node * creat(char *pre,char *mid,int len)  //通过前序遍历和后序遍历构造二叉树
{
char *i;
int k;
struct node *root1;
if(len==0)
return NULL;
root1=(struct node *)malloc(sizeof(struct node));
root1->data=*pre;
for(i=&mid[0],k=0; i<mid+len; i++,k++)
{
if(*i== *pre)
break;
}
root1->left=creat(pre+1,mid,k);
root1->right=creat(pre+1+k,i+1,len-1-k);
return root1;
}

void Lastput(struct node  * root)  //后序遍历
{
if(root)
{
Lastput(root->left);
Lastput(root->right);
printf("%c",root->data);
}
}

void sort(struct node *root)  //层次遍历
{
struct node *q[1005];
int head=0,tail=0;
if(!root)
return;
q[tail++]=root;
while(head<tail)
{
printf("%c",q[head]->data);
if(q[head]->left)
q[tail++]=q[head]->left;
if(q[head]->right)
q[tail++]=q[head]->right;
head++;
}
}
int main()
{
int t,n;
char pre[55];
char mid[55];
struct node *root;
while(~scanf("%d",&t))
{
while(t--)
{
root=(struct node *)malloc(sizeof(struct node));
n=0;
scanf("%s%s",pre,mid);
n=strlen(mid);
root=creat(pre,mid,n);
Lastput(root);
printf("\n");
sort(root);
printf("\n");
}
}
return 0;
}
c++版
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

char a[55],b[55];
struct node
{
char data;
struct node *left,*right;
};

struct node *creat(char *pre,char *mid,int len)
{
node *p=new node;
char c;
int i;
if(len==0)  return NULL;
p->data=pre[0];
c=pre[0];
for(i=0; i<len; i++)
{
if(c==mid[i])
break;
}
p->left=creat(pre+1,mid,i);
p->right=creat(pre+i+1,mid+1+i,len-i-1);
return p;
};
void lastout(node *root)
{
if(root)
{
lastout(root->left);
lastout(root->right);
cout<<root->data;
}
}
void put(node *root)
{
queue<node *>q;
if(!root)  return;
q.push(root);
while(!q.empty())
{
cout<<q.front()->data;
if(q.front()->left)
q.push(q.front()->left);
if(q.front()->right)
q.push(q.front()->right);
q.pop();
}
}
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
cin>>a>>b;
node *root;
root=creat(a,b,strlen(a));
lastout(root);
cout<<endl;
put(root);
cout<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息