1020. Tree Traversals (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题意:
1.输入一个正整数N表示二叉树有N个节点
2.输入后序的顺序
3.输入中序的顺序
4.输出层次遍历的顺序
坑:
层次的输出需从左到右方可
思路:
1.后序:左->右->根
2.中序:左->根->右
3.由此可知,根节点就是后序的最后一个节点,而根据得到的根节点,可由中序得知左右子树,递归可得树的全貌
- 例如题中所给样例:
- 后序:2 3 1 5 7 6 4
- 中序:1 2 3 4 5 6 7
- 拆分:根:4 左子树:1 2 3 右子树:5 6 7
- 左子树拆分:根:1 左子树:空 右子树:2 3
- 右子树拆分:根:6 左子树:5 右子树:7
4.层次顺序的存储方法是数组(要开得够大),将根节点存储在下标为location的位置后,其左子树根节点存储在下标为location*2,右子树则是location*2+1;
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int postorder[50],inorder[50];
int level[10000];
void findCeng(int ps,int pe,int is,int ie,int location)
{
if(pe<0||ie<0||ps>pe||is>ie)return;
int root=postorder[pe];
level[location]=root;
int im=0,pm=0;
if(ps==pe)return;
for(int i=is;i<=ie;i++)
{
if(inorder[i]==root)
{
im=i;
break;
}
}
for(int i=ps;i<=pe;i++)
{
bool flag=false;
for(int j=is;j<im;j++)
{
if(postorder[i]==inorder[j])
{
flag=true;
break;
}
}
if(!flag)
{
pm=i;
break;
}
}
findCeng(ps,pm-1,is,im-1,location*2);
findCeng(pm,pe-1,im+1,ie,location*2+1);
}
int main()
{
int N;
cin>>N;
memset(level,0,sizeof(level));
for(int i=0;i<N;i++)cin>>postorder[i];
for(int i=0;i<N;i++)cin>>inorder[i];
findCeng(0,N-1,0,N-1,1);
int count=0;
for(int i=1;;i++)
{
if(level[i]!=0)
{
count++;
if(count==N)
{
cout<<level[i]<<endl;
break;
}
else cout<<level[i]<<" ";
}
}
return 0;
}
附上更简洁的代码(别的大大写的哈)
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int pod[35];
int iod[35];
int lod[10000];
void dfs(int p1, int p2, int q1, int q2, int od){
if(p1 > p2 || q1 > q2) return ;
int i = p1;
while(iod[i] != pod[q2]) i++;
lod[od] = pod[q2];
dfs(p1, i-1, q1, q1+i-1-p1, 2*od);
dfs(i+1, p2, q1+i-p1, q2-1, 2*od+1);
}
int main(){
scanf("%d",&n);
memset(lod,0,sizeof(lod));
for(int i = 0; i < n; i++){
scanf("%d",&pod[i]);
}
for(int i = 0; i < n; i++){
scanf("%d",&iod[i]);
}
dfs(0, n-1, 0, n-1, 1);
int flag = 1;
for(int i = 1; i < 10000; i++){
if(flag && lod[i] != 0){
printf("%d",lod[i]);
flag = 0;
}
else if(!flag && lod[i]){
printf(" %d",lod[i]);
}
}
return 0;
}