1043. Is It a Binary Search Tree (25)

#include <iostream>
#include <vector>

using namespace std;

struct node
{
	int lchild, rchild, key;
}tree[1010];

int pre[1010], r = 1, first = 1, choose, n;
vector<int> v;

int buildbst(int a, int b)
{
	int root = r++;
	tree[root].key = pre[a];

	int i;
	for(i = a + 1; i <= b; i++)
	{
		if(choose == 0 && pre[i] >= pre[a])
		{
			break;
		}
		else if(choose == 1 && pre[i] < pre[a])
		{
			break;
		}
	}

	if(i - a >= 2)
	{
		tree[root].lchild = buildbst(a + 1, i - 1);
	}
	if(b >= i)
	{
		tree[root].rchild = buildbst(i, b);
	}

	return root;
}

void inorder(int root)
{
	int l = tree[root].lchild, r = tree[root].rchild;
	if(l != -1)
	{
		inorder(l);
	}

	v.push_back(tree[root].key);

	if(r != -1)
	{
		inorder(r);
	}
}

void postorder(int root)
{
	int l = tree[root].lchild, r = tree[root].rchild;
	if(l != -1)
	{
		postorder(l);
	}
	if(r != -1)
	{
		postorder(r);
	}

	if(first == 1)
	{
		first = 0;
	}
	else
	{
		printf(" ");
	}

	printf("%d", tree[root].key);
}

int judge()
{
	int i;
	for(i = 1; i <= n - 1; i++)
	{
		if(choose == 0 && v[i] < v[i - 1])
		{
			return 0;
		}
		else if(choose == 1 && v[i] > v[i - 1])
		{
			return 0;
		}
	}

	return 1;
}

void init()
{
	int i;
	for(i = 1; i <= n; i++)
	{
		tree[i].lchild = tree[i].rchild = -1;
	}

	r = 1;
}

int main()
{
	scanf("%d", &n);

	int i;
	for(i = 1; i <= n; i++)
	{
		scanf("%d", &pre[i]);
	}

	int flag = 0;
	for(i = 0; i <= 1; i++)
	{
		choose = i;
		init();

		buildbst(1, n);

		v.clear();
		inorder(1);

		if(judge() == 1)
		{
			flag = 1;

			printf("YES\n");
			postorder(1);
			printf("\n");

			break;
		}
	}

	if(flag == 0)
	{
		printf("NO\n");
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-23 17:05  王景迁  阅读(4)  评论(0)    收藏  举报

导航