AT_abc255_f [ABC255F] Pre-order and In-order 题解

初赛常考题目:由先序遍历和中序遍历构建二叉树

解题思路

具体的,我们会从先序遍历中取出第一个数,即当前树的根。

拿样例出来:

先序遍历:1 3 5 6 4 2
中序遍历:3 5 1 4 6 2

这里 1 就是我们的根,然后根据中序遍历将树分成了两个部分:

先序遍历:1 | 3 5 | 6 4 2
中序遍历:3 5 | 1 | 4 6 2

于是就有了两颗子树,我们再分别对其重复上述过程,即可得到整棵树。具体的实现递归即可,代码里会有注释。

参考代码

#include<bits/stdc++.h>
#include<queue>
#include<vector>
using namespace std;
int n;
int a[200005],b[200005];
int x;
int l[200005],r[200005];
int dfs(int il,int ir,int jl,int jr){
	int root=a[jl];//先序遍历的第一个,即根
	int pos=b[root];//在另一个序列中根的位置
	if(il>pos || ir<pos){//冲突了,则无解
		cout<<-1;
		exit(0);
	}
	if(il<pos){//递归左子树,传回来的根为左儿子
		l[root]=dfs(il,pos-1,jl+1,jl+pos-il);
	}
	if(ir>pos){//同理
		r[root]=dfs(pos+1,ir,jl+1+pos-il,jr);
	}
	return root;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	for(int i=1;i<=n;i++){
		cin>>x;
		b[x]=i;
	}
	int c=dfs(1,n,1,n);
	if(c!=1){
		cout<<-1;
		return 0;
	}
	for(int i=1;i<=n;i++){
		cout<<l[i]<<' '<<r[i]<<endl;
	}
	return 0;
}
posted @ 2026-08-21 16:17  tangkaiming  阅读(2)  评论(0)    收藏  举报