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

数据结构,二叉树已知后续中序,建树,层次遍历;

2016-05-15 21:09 501 查看
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:
4 1 6 3 5 7 2


#include<bits/stdc++.h>
#include <cstring>
using namespace std;
struct node
{
int x;
node *l,*r;
};
int A[50],B[50];
queue<node*>Q;
node* build(int l,int r,int L,int R)
{
node *head;
if(l>r)
return NULL;
head=new node;
head->x=A[R];
int i;
for(i=l; i<=r&&A[R]!=B[i]; i++);
head->l=build(l,i-1,L,L+(i-1-l));
head->r=build(i+1,r,L+(i-l),R-1);

return head;
}
void ceng(node *head)
{
while(!Q.empty())
Q.pop();
Q.push(head);
node *tmp;
int first=1;
while(!Q.empty())
{
tmp=Q.front(),Q.pop();
if(first)
first=0;
else
printf(" ");
printf("%d",tmp->x);
if(tmp->l)
Q.push(tmp->l);
if(tmp->r)
Q.push(tmp->r);
}
printf("\n");
}
int main()
{
int n;
node *head;
cin>>n;
for(int i=0; i<n; i++)
scanf("%d",&A[i]);
for(int j=0; j<n; j++)
scanf("%d",&B[j]);
head=build(0,n-1,0,n-1);
ceng(head);
return 0;
}

已知先序中序,求后序;

#include <bits/stdc++.h>
#define LL long long
using namespace std;
char s[100],str[100];
struct node
{
char c;
node *l,*r;
};
node *build(int l,int r,int L,int R)
{
node *head;
if(l>r)
return NULL;
head=new node;
head->c=s[l];
int i;
for(i=L;str[i]!=s[l];i++);
head->l=build(l+1,l+(i-L),L,i-1);
head->r=build(l+(i-L+1),r,i+1,R);
return head;
}
void hou(node *head)
{
if(head->l)
hou(head->l);
if(head->r)
hou(head->r);
printf("%c",head->c);
}
void ceng(node *head)
{
queue<node*>Q;
Q.push(head);
node *tmp;
while(!Q.empty())
{
tmp=Q.front(),Q.pop();
printf("%c",tmp->c);
if(tmp->l)
Q.push(tmp->l);
if(tmp->r)
Q.push(tmp->r);

}
printf("\n");
}
int main()
{
int t;
node *head;
cin>>t;
while(t--)
{
scanf("%s%s",s,str);
int len=strlen(s);
head=build(0,len-1,0,len-1);
hou(head);
printf("\n");
ceng(head);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: