1043. Is It a Binary Search Tree

本文提供了一种方法来判断给定的先序遍历序列是否对应于有效的二叉搜索树(BST)或其镜像。通过递归检查左子树和右子树的性质,确保所有元素都符合BST的定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题……没想到镜像BST和BST先序怎么转换,直接复制了一下函数。
#include <stdio.h>
#include <stdlib.h>

int IsBST(int Pre[],int begin,int end,int Post[],int PosBegin,int PosEnd);
int IsMBST(int Pre[], int begin, int end, int Post[], int PosBegin, int PosEnd);
int main()
{
	int n,i,Is;
	scanf("%d", &n);
	int *Pre = (int*)malloc(sizeof(int)*n);
	int *Post = (int*)malloc(sizeof(int)*n);
	for (i = 0; i < n; i++)
		scanf("%d", &Pre[i]);
	Is = IsBST(Pre, 0, n - 1, Post,0,n-1);

	if (Is) {
		printf("YES\n");
		for (i = 0; i < n - 1; i++)
			printf("%d ", Post[i]);
		printf("%d", Post[n-1]);
	}
	else if (Is = IsMBST(Pre, 0, n - 1, Post, 0, n - 1)) {
		printf("YES\n");
		for (i = 0; i < n - 1; i++)
			printf("%d ", Post[i]);
		printf("%d", Post[n - 1]);
	}else 
		printf("NO");
        free(Pre);free(Post);
	return 0;
}

int IsBST(int Pre[], int begin, int end, int Post[],int PosBegin,int PosEnd)
{
	int i,Root = Pre[begin],Pos,LeftSize,RightSize;
	if (begin > end)/*树空*/
		return 1;
	for (i = begin + 1; i <= end; i++) {
		if (Pre[i] >= Root)
			break;
	}
	Pos = i;
	while (i <= end)
		if (Pre[i] < Root)
			return 0;
		else i++;
	
	Post[ PosEnd ] = Root;
	LeftSize = Pos - begin - 1;
	RightSize = end - Pos + 1;
	return IsBST(Pre, begin + 1, Pos - 1, Post,PosBegin,PosBegin+LeftSize-1) && IsBST(Pre, Pos, end, Post,PosEnd-RightSize,PosEnd-1);
}

int IsMBST(int Pre[], int begin, int end, int Post[], int PosBegin, int PosEnd)
{
	int i, Root = Pre[begin], Pos, LeftSize, RightSize;
	if (begin > end)/*树空*/
		return 1;
	for (i = begin + 1; i <= end; i++) {
		if (Pre[i] < Root)
			break;
	}
	Pos = i;
	while (i <= end)
		if (Pre[i] >= Root)
			return 0;
		else i++;

	Post[PosEnd] = Root;
	LeftSize = Pos - begin - 1;
	RightSize = end - Pos + 1;
	return IsMBST(Pre, begin + 1, Pos - 1, Post, PosBegin, PosBegin + LeftSize - 1) && IsMBST(Pre, Pos, end, Post, PosEnd - RightSize, PosEnd - 1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值