【题解】【AcWing】1527. 判断二叉搜索树

109 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1527. 判断二叉搜索树

原题传送:AcWing 1527. 判断二叉搜索树

二叉搜索树(BST)递归定义为具有以下属性的二叉树:

  • 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值
  • 若它的右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值
  • 它的左、右子树也分别为二叉搜索树

我们将二叉搜索树镜面翻转得到的树称为二叉搜索树的镜像。

现在,给定一个整数序列,请你判断它是否可能是某个二叉搜索树或其镜像进行前序遍历的结果。

输入格式

第一行包含整数 NN ,表示节点数量。

第二行包含 NN 个整数。

输出格式

如果给定整数序列是某个二叉搜索树或其镜像的前序遍历序列,则在第一行输出 YES,否则输出 NO

如果你的答案是 YES,则还需要在第二行输出这棵树的后序遍历序列。

数据范围

1N10001 \le N \le 1000

输入样例1:

7
8 6 5 7 10 8 11

输出样例1:

YES
5 7 6 8 11 10 8

输入样例2:

7
8 10 11 8 6 7 5

输出样例2:

YES
11 8 10 7 5 6 8

输入样例3:

7
8 6 8 5 10 9 11

输出样例3:

NO

思路:

二叉搜索树的值的正序或逆序序列为中序遍历,和前序遍历判断能否构成一棵树,正序序列相同值的左边第一个为原序,右边的第一个为镜像序列。

题解:

#include<bits/stdc++.h>

using namespace std;

const int N = 1010;

int n;
int preorder[N], inorder[N];
int postorder[N], cnt;

bool build(int il, int ir, int pl, int pr, int type)
{
	if(il > ir)
		return true;
		
	int root = preorder[pl];
	int k;
	if(!type)
	{
		for(k = il; k <= ir; k++)
			if(inorder[k] == root)
				break;
		if(k > ir)
			return false;
	}
	else
	{
		for(k = ir; k >= il; k--)
			if(inorder[k] == root)
				break;
		if(k < il)
			return false;
	}
	
	bool res = true;
	if(!build(il, k - 1, pl + 1, pl + 1 + (k - 1 - il), type))
		res = false;
	if(!build(k + 1, ir, pl + 1 + (k - 1 - il) + 1, pr, type))
		res = false;
		
	postorder[cnt++] = root;
	return res;
}

int main()
{	
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		cin >> preorder[i];
		inorder[i] = preorder[i];
	}
		
	sort(inorder, inorder + n);
	
	if(build(0, n - 1, 0, n - 1, 0))
	{
		cout << "YES" << endl;
		cout << postorder[0];
		for(int i = 1; i < n; i++)
			cout << " " << postorder[i];
		cout << endl;
	}
	else
	{
		reverse(inorder, inorder + n);
		cnt = 0;
		if(build(0, n - 1, 0, n - 1, 1))
		{
			cout << "YES" << endl;
			cout << postorder[0];
			for(int i = 1; i < n; i++)
				cout << " " << postorder[i];
			cout << endl;
		}
		else
			cout << "NO" << endl;	
	}
	
	return 0;
}