PAT1043-Is It a Binary Search Tree

本文详细介绍了如何根据给定数列构建二叉树,并通过两种不同的遍历方式(前序遍历和后序遍历)验证是否存在数列匹配的情况。实现过程包括数列到二叉树的映射、遍历算法的编写以及最终的比较逻辑,旨在解决特定数列与二叉树遍历结果的匹配问题。

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1043

想法是根据给的数列建二叉树
根左子树右子树遍历
根右子树左子树遍历
若给的数列跟上述两个遍历得到的数列某个相等则YES,否则NO

C语言源码:

#include<stdio.h>
#include<stdlib.h>
typedef struct Bitree
{
	int data;
	struct Bitree *lchild,*rchild;
}Bitree;
int A[1010],B[1010],C[1010],D[1010],topa,topb,topc,topd;
Bitree *create(Bitree *root,int x)
{
	Bitree *q,*p;
	p=(Bitree *)malloc(sizeof(Bitree));
	p->data=x;
	p->lchild=NULL;
	p->rchild=NULL;
	if(!root)
		return p;
	else
	{
		q=root;
		while((q->data>x&&q->lchild)||(q->data<=x&&q->rchild))
		{
			if(q->data>x)
				q=q->lchild;
			else
				q=q->rchild;
		}
		if(q->data>x)
			q->lchild=p;
		else
			q->rchild=p;
		return root;
	}
}
void Pre1(Bitree *root)
{
	if(root)
	{
		A[topa++]=root->data;
		Pre1(root->lchild);
		Pre1(root->rchild);
	}
}
void Pre2(Bitree *root)
{
	if(root)
	{
		B[topb++]=root->data;
		Pre2(root->rchild);
		Pre2(root->lchild);
	}
}
void Post1(Bitree *root)
{
	if(root)
	{
		Post1(root->lchild);
		Post1(root->rchild);
		C[topc++]=root->data;
	}
}
void Post2(Bitree *root)
{
	if(root)
	{
		Post2(root->rchild);
		Post2(root->lchild);
		D[topd++]=root->data;
	}
}
int main()
{
	int n,i;
	Bitree *root;
	int s[1010];
	int flag;
	topa=0;topb=0;topc=0;topd=0;root=NULL;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&s[i]);
		root=create(root,s[i]);
	}
	Pre1(root);
	Pre2(root);
	Post1(root);
	Post2(root);
	flag=0;
	for(i=0;i<n;i++)
		if(A[i]!=s[i])
			break;
	if(i==n)
		flag=1;
	for(i=0;i<n;i++)
		if(B[i]!=s[i])
			break;
	if(i==n)
		flag=2;
	if(flag==1)
	{
		printf("YES\n");
		for(i=0;i<n-1;i++)
			printf("%d ",C[i]);
		printf("%d\n",C[i]);
	}
	else
		if(flag==2)
		{
			printf("YES\n");
			for(i=0;i<n-1;i++)
				printf("%d ",D[i]);
			printf("%d\n",D[i]);
		}
		else
			printf("NO\n");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值