7-70 树的遍历(已知前序||后序 和中序求层序遍历)
7-70 树的遍历 (25 分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
该题是已知后序和中序 求层序
先用两个数组pre和in数组将后续和中序存起来,然后再利用递归把大问题化成小问题,因为后序是LRD所以最后一个一定是根节点,在中序LDR里面找到这个根节点之后,左边的就是在根节点左子树上的结点,右边的就是在根节点右子树上的结点,再利用数组l,r把根节点的左右结点存起来
#include<iostream>
#include<map>
#include<queue>
using namespace std;
map<int,int>l,r;
int hou[1010];//后序遍历数组
int in[1010];//中序遍历数组
int n;
queue<int>q;
int build(int hl,int hr,int il,int ir)
{
if(hl>hr||il>ir) return 0;
int root=il;
//找到后序遍历根节点在中序遍历中的位置
while(root<=ir&&in[root]!=hou[hr]) root++;
int cnt=root-il;
l[hou[hr]]=build(hl,hl+cnt-1,il,root-1);
r[hou[hr]]=build(hl+cnt,hr-1,root+1,ir);
return hou[hr];
}
void print(int root)//层序遍历输出
{
q.push(root);
cout<<root;
int sum=1;
if(sum!=n) cout<<" ";
while(q.size())
{
root=q.front();
q.pop();
if(l[root])
{
cout<<l[root];
q.push(l[root]);
sum++;
if(sum!=n) cout<<" ";
}
if(r[root])
{
cout<<r[root];
sum++;
q.push(r[root]);
if(sum!=n) cout<<" ";
}
if(sum==n) break;
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>hou[i];
}
for(int i=1;i<=n;i++)
{
cin>>in[i];
}
int root=build(1,n,1,n);
print(root);
return 0;
}
下面是已知前序和中序求层序:
#include<iostream>
#include<map>
#include<queue>
using namespace std;
map<int,int>l,r;
int pre[1010];//前序遍历数组
int in[1010];//中序遍历数组
int n;
queue<int>q;
int build(int pl,int pr,int il,int ir)
{
if(pl>pr||il>ir)
{
return 0;
}
int root=il;
while(root<=ir&&in[root]!=pre[pl])//找到前序遍历根节点在中序遍历的位置
{
root++;
}
int cnt=root-il;
l[pre[pl]]=build(pl+1,pl+cnt,il,root-1);
r[pre[pl]]=build(pl+cnt+1,pr,root+1,ir);
return pre[pl];
}
void print(int root)//层序遍历输出
{
q.push(root);
cout<<root<<" ";
int sum=1;
while(q.size())
{
root=q.front();
q.pop();
if(l[root])
{
cout<<l[root]<<" ";
q.push(l[root]);
sum++;
}
if(r[root])
{
cout<<r[root]<<" ";
sum++;
q.push(r[root]);
}
if(sum==n) break;
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>pre[i];
}
for(int i=1;i<=n;i++)
{
cin>>in[i];
}
int root=build(1,n,1,n);
print(root);
return 0;
}
//7
//10 9 7 8 12 11 13
//7 9 8 10 11 12 13