二叉树采用二叉链表存储,要求根据给定的后序遍历序列和中序遍历序列建立二叉树,并输出二叉树的深度及其先序遍历序列。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据的第一行输入结点数n(1≤n≤10),第二、三行各输入n个整数,分别表示二叉树的后序遍历序列和中序遍历序列。
输出格式:
对于每组测试,在一行上分别输出该二叉树的深度及其先序遍历序列。每两个数据之间留一个空格。
输入样例:
9
7 4 2 8 9 5 6 3 1 9
4 7 2 1 8 5 9 3 6
输出样例:
4 1 2 4 7 3 5 8 9 6
来源:
黄龙军, 等. 数据结构与算法(Python版),上海: 上海交通大学出版社, 2023. ISBN: 9787313280732
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<iostream>
using namespace std;
const int N = 20;
int a[N];
int b[N];
int res[N];
int t=0;
int max(int a,int b){
return a>b?a:b;
}
int dfs(int l1,int r1,int l2,int r2){
if(l1>r1)return 0;
res[t++]=a[r1];
int temp=0;
for(int i=l2;i<=r2;i++){
if(a[r1]==b[i]){
temp=i;
break;
}
}
int a1 = dfs(l1,l1+temp-l2-1,l2,temp-1);
int a2 = dfs(l1+temp-l2,r1-1,temp+1,r2);
return max(a1,a2)+1;
}
int main()
{
int n;
while(cin>>n){
t=0;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)cin>>b[i];
printf("%d ",dfs(0,n-1,0,n-1));
for(int i=0;i<t-1;i++)cout<<res[i]<<' ';
cout<<res[t-1];
cout<<endl;
}
return 0;
}