PAT A 1043 Is It a Binary Search Tree (25 分)

一、思路

step1:建树
typedef struct node
{
    int data;
    struct node *lchild, *rchild;
}node;
node *root = NULL;
void create( node *&T, int key )
{
    if( !T )
    {
        T = (node*)malloc(sizeof(node));
        T->data = key;
        T->lchild = T->rchild = NULL;
    }
    else if( key < T->data )
        create(T->lchild, key);
    else create(T->rchild, key);
}
step2:比较是否为先序序列,若不是则交换所有结点左右子树再比较
bool preorder( node *&t, int tag, node *root )//返回是否符合BST定义,tag为1则含交换子树操作;
{
	if( !t )
		return true;
	if( t == root )
		index = 0;
	if( t->data != pre[index++] )
		return false;
	if( tag )
		swap(t->lchild, t->rchild);
	return ( preorder(t->lchild, tag, root) && preorder(t->rchild, tag, root) );
}
step3:输出
void postorder( node *T )
{
    if( T )
    {
        postorder(T->lchild);
        postorder(T->rchild);
        printf("%s%d", index++ ? " ":"", T->data);//index为全局变量
    }
}

二、代码

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct node
{
	int data;
	struct node *lchild, *rchild;
};
int index = 0;
vector<int> pre(1000);
void create( node *&t, int key )
{
	if( !t )
	{
		t = new node;
		t->data = key;
		t->lchild = t->rchild = NULL;
	}
	else if( key < t->data )
		create(t->lchild, key);
	else create(t->rchild, key);
}
bool preorder( node *&t, int tag, node *root )
{
	if( !t )
		return true;
	if( t == root )
		index = 0;
	if( t->data != pre[index++] )
		return false;
	if( tag )
		swap(t->lchild, t->rchild);
	return ( preorder(t->lchild, tag, root) && preorder(t->rchild, tag, root) );
}
void postorder( node *t, node *root )
{
	if( t )
	{
		postorder(t->lchild, root);
		postorder(t->rchild, root);
		printf("%d%s", t->data , t == root ? "":" ");
	}
}
int main()
{
	int N;
	node *root = NULL;
	scanf("%d", &N);
	for( int i = 0; i < N; ++i )
	{
		scanf("%d", &pre[i]);
		create(root, pre[i]);
	}
	if( preorder(root, 0, root) || preorder(root, 1, root) )
	{
		printf("YES\n");
		postorder(root, root);
	}
	else printf("NO");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值