已知前中序遍历,求一颗二叉树,可能不合法,需要判
  • 板块学术版
  • 楼主high_sky
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/1/28 21:18
  • 上次更新2024/1/28 23:16:46
查看原帖
已知前中序遍历,求一颗二叉树,可能不合法,需要判
701202
high_sky楼主2024/1/28 21:18

rt,代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <set>
#include <stack>
#include <map>
#include <stdlib.h>
#include <sstream>
#include <climits>
//#define rep(i,a,b) for (int (i) = (a);(i) <= (b);(i) ++)
//#define req(i,a,b) for (int (i) = (b);(i) >= (a);(i) --)
//#define int long long
#define N 200005
using namespace std;
struct tr{
	int lson,rson;
}tr[N]; 
int n,a[N],b[N],mp[N],k = 1,vis[N],bj[N];
void dfs(int cur) {
	if (k > n) return;
	int t = mp[cur];
	if (vis[b[t + 1]] && vis[b[t - 1]]) return;
	vis[cur] = 1;
	if (t > 1 && !vis[b[t - 1]] && mp[a[k + 1]] < t) {
		k ++;
		tr[cur].lson = a[k];
		vis[a[k]] = 1;
		dfs(a[k]);
	}
	if (t < n && !vis[b[t + 1]] && mp[a[k + 1]] > t) {
		k ++;
		tr[cur].rson = a[k];
		vis[a[k]] = 1;
		dfs(a[k]);
	}
}
signed main(){
	cin >> n;
	for (int i = 1;i <= n;i ++) cin >> a[i];
	for (int j = 1;j <= n;j ++) cin >> b[j],mp[b[j]] = j;
	vis[0] = vis[n + 1] = 1;
	if (a[1] != 1) cout <<-1ll,exit(0);
	dfs(1);
	if (!tr[1].lson && !tr[1].rson) cout << -1ll,exit(0);
	memset(vis,0,sizeof vis);
	for (int i = 1;i <= n;i ++) {
		if (tr[i].lson) {
			if (vis[tr[i].lson]) cout << -1ll,exit(0);
			vis[tr[i].lson] = 1;
		}
		if (tr[i].rson) {
			if (vis[tr[i].rson]) cout << -1ll,exit(0);
			vis[tr[i].rson] = 1;
		}
	}
	vis[1] = 1;
	for (int i = 1;i <= n;i ++)
		if (!vis[i] || (tr[i].lson && !(mp[tr[i].lson] < mp[i])) || (tr[i].rson && !(mp[tr[i].rson] > mp[i])))
			cout << -1ll,exit(0);
	for (int i = 1;i <= n;i ++)
		cout << tr[i].lson << ' ' << tr[i].rson << endl;
	return 0;
}

如何改(判非法时有问题)?

2024/1/28 21:18
加载中...