题目描述:
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
解题思路:
这题是给定后序和中序的遍历,可以通过后序确定根节点,在通过根节点将中序分为左子树和右子树和根节点,然后通过左子树和右子树可以将后序也分成左子树和右子树和根节点,然后其实就是重复这个过程来建树,最后层序遍历用广搜就行了
AC代码:
#include <iostream>
#include<stdio.h>
using namespace std;
int tree[5000];
int a;
void gettree(int b[500],int c[500],int num,int tb,int tc)
{
if(tb==0||tc==0)
{
return;
}
int b1[35];
int c1[35];
int tb1=0;
int tc1=0;
int n=0;
for(n=0;n<tc;n++)
{
if(c[n]==b[tb-1])
{
gettree(b1,c1,num*2+1,tb1,tc1);
tree[num]=c[n];
break;
}
b1[tb1]=b[n];
tb1++;
c1[tc1]=c[n];
tc1++;
}
tb1=0;
tc1=0;
int u=n;
n++;
while(n<tc)
{
b1[tb1]=b[u];
c1[tc1]=c[n];
n++;
u++;
tb1++;
tc1++;
}
gettree(b1,c1,num*2+2,tb1,tc1);
}
int flag6=0;
void bfs(int dui[35],int num)
{
if(num==0)
{
return;
}
int dui1[35];
int num1=0;
for(int n=0;n<num;n++)
{
if(flag6==0)
{
printf("%d",tree[dui[n]]);
flag6=1;
}
else
{
printf(" %d",tree[dui[n]]);
}
if(tree[dui[n]*2+1]!=-1)
{
dui1[num1]=dui[n]*2+1;
num1++;
}
if(tree[dui[n]*2+2]!=-1)
{
dui1[num1]=dui[n]*2+2;
num1++;
}
}
bfs(dui1,num1);
}
int main(int argc, char *argv[]) {
scanf("%d",&a);
int b[500],c[500];
for(int n=0;n<5000;n++)
{
tree[n]=-1;
}
for(int n=0;n<2;n++)
{
for(int m=0;m<a;m++)
{
int t;
scanf("%d",&t);
if(n==0)
{
b[m]=t;
}
else
{
c[m]=t;
}
}
}
gettree(b,c,0,a,a);
int dui[200];
dui[0]=0;
bfs(dui,1);
return 0;
}
来源:https://blog.csdn.net/weixin_45415649/article/details/99233767