1
2
3

L2-004 这是二叉搜索树吗?

L2-004 这是二叉搜索树吗?(25分)

题意

给你一个搜索二叉树的前序遍历(可能是错的),让你检测它或者它的镜像是不是真的搜索二叉树,是的话输出它的后续遍历

思路

直接模拟一遍,比较考验基本功。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
#define mem(a, b) memset(a, b, sizeof(a))
#define pb push_back
#define ll long long
using namespace std;
const double PI = acos(-1.0);
const int N = 2e5 + 10;
const int mod = 1e9 + 7;
/////////////////////////////////////////
typedef struct node
{
	struct node *l, *r;
	int data;
} tr;
vector<int> a;
vector<int> pre;
vector<int> post;
tr *insert_(tr *rt, int cur)
{
	if (rt == NULL)
	{
		rt = new tr;
		rt->data = cur;
		rt->l = rt->r = NULL;
	}
	else
	{
		if (rt->data > cur)
		{
			rt->l = insert_(rt->l, cur);
		}
		else
		{
			rt->r = insert_(rt->r, cur);
		}
	}
	return rt;
}
void pre_(tr *rt)
{
	if (rt != NULL)
	{
		pre.pb(rt->data);
		pre_(rt->l);
		pre_(rt->r);
	}
	return;
}
void post_(tr *rt)
{
	if (rt != NULL)
	{
		post_(rt->l);
		post_(rt->r);
		post.pb(rt->data);
	}
	return;
}
tr *aaaa(tr *rt)
{
	if (rt == NULL)
	{
		return NULL;
	}
	rt->l = aaaa(rt->l);
	rt->r = aaaa(rt->r);
	swap(rt->l, rt->r);
	return rt;
}
int main()
{
	int n;
	cin >> n;
	tr *rt = NULL;
	for (int i = 1; i <= n; i++)
	{
		int cur;
		cin >> cur;
		a.pb(cur);
		rt = insert_(rt, cur);
	}
	pre_(rt);
	int ok = 1;
	for (int i = 0; i < n; i++)
	{
		if (a[i] != pre[i])
		{
			ok = 0;
			break;
		}
	}
	if (ok)
	{
		post_(rt);
		cout << "YES" << endl;
		for (int i = 0; i < n-1; i++)
		{
			cout << post[i] << " ";
		}
		cout<<post[n-1];
		return 0;
	}
	pre.clear();
	rt = aaaa(rt);
	pre_(rt);
	for (int i = 0; i < n; i++)
	{
		if (a[i] != pre[i])
		{
			ok = 0;
			cout << "NO" << endl;
			return 0;
		}
	}
	post_(rt);
	cout << "YES" << endl;
	for (int i = 0; i < n-1; i++)
	{
		cout << post[i] << " ";
	}
	cout<<post[n-1];
	return 0;
}
posted @ 2020-10-04 16:23  Arance  阅读(95)  评论(0编辑  收藏  举报