团体程序设计天梯赛L2-004 这是二叉搜索树吗?(数据结构)

该博客探讨了如何判断一个给定的整数序列是否符合二叉搜索树或其镜像的前序遍历结果。通过递归地检查每个节点的键值条件,可以验证序列的合法性。
摘要由CSDN通过智能技术生成

思路:对于一颗合法的二叉搜索树,那么即满足对于区间[l,r],存在一个点i,a[l]<a[i]<a[r],那么就区间递归下去判断就可以了


#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;
const int maxn = 1005;
int a[maxn];
int check1(int l,int r)
{
	if(l>=r)
		return 1;
	int key = r;
	for(int i = l+1;i<=r;i++)
		if(a[l]<=a[i])
		{
			key = i;
			break;
		}
	for(int i = key+1;i<=r;i++)
		if(a[l]>a[i])
			return 0;
	return check1(l+1,key-1)&&check1(key,r);
}
int check2(int l,int r)
{
	if(l>=r)
		return 1;
	int key = r;
	for(int i = l+1;i<=r;i++)
		if(a[l]>=a[i])
		{
			key = i;
			break;
		}
	for(int i = key+1;i<=r;i++)
		if(a[l]<a[i])
			return 0;
	return check2(l+1,key-1)&&check2(key,r);
}
struct Node
{
	int val;
	Node *lchild;
	Node *rchild;
};
Node *root = NULL;
Node* build(Node *t,int key)
{
	if(t==NULL)
	{
		Node*p = new Node;
		p->val = key;
		p->lchild = NULL;
		p->rchild = NULL;
		return p;
	}
	if(key >= t->val)
		t->rchild = build(t->rchild,key);
	else
		t->lchild = build(t->lchild,key);
	return t;
}

Node* rbuild(Node *t,int key)
{
	if(t==NULL)
	{
		Node*p = new Node;
		p->val = key;
		p->lchild = NULL;
		p->rchild = NULL;
		return p;
	}
	if(key < t->val)
		t->rchild = rbuild(t->rchild,key);
	else
		t->lchild = rbuild(t->lchild,key);
	return t;
}

void print(Node *t)
{
	if(t==NULL)
		return;
	print(t->lchild);
	print(t->rchild);
	if(t!=root)
	  printf("%d ",t->val);
}
int main()
{
    int n;
	scanf("%d",&n);
	for(int i = 0;i<n;i++)
		scanf("%d",&a[i]);
	int flag1 = check1(0,n-1);
	int flag2 = check2(0,n-1);
	if(!(flag1||flag2))
	{
		printf("NO\n");
		return 0;
	}
	else if (flag1)
		for(int i = 0;i<n;i++)
			root = build(root,a[i]);
	else if (flag2)
		for(int i = 0;i<n;i++)
			root = rbuild(root,a[i]);
	printf("YES\n");
	print(root);
	printf("%d"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值