1043 Is It a Binary Search Tree

1043 Is It a Binary Search Tree

题目大意

将一个二叉排序树或者其镜像树的先序序列,转为后序序列

算法思想

  • 先按不是镜像来做,将二叉排序树的后序求出来,如果大小不是n,则有可能镜像有可能是错二叉排序树,就可以按镜像处理一次,求出其二叉排序树后序序列,如果大小还不是n,就是错的二叉排序树

代码

#include<iostream>
#include<vector>
using namespace std;
vector<int>pre, post;
bool mir = false;
int n;
void turnpost(int x, int y) {//转后序
	if (x > y)
		return;
	int i = x + 1;
	int j = y;
	if (!mir) {//不是镜像
		while (i <= y && pre[i] < pre[x])
			i++;
		while (j > x && pre[j] >= pre[x])
			j--;
	}
	else {//是镜像
		while (i <= y && pre[i] >= pre[x])
			i++;
		while (j > x && pre[j] < pre[x])
			j--;
	}
	if (j != x)//有左子树
		turnpost(x + 1, j);
	if (i != y + 1)//有右子树
		turnpost(i, y);
	post.push_back(pre[x]);
	return;
}
int main() {
	cin >> n;
	pre.resize(n);
	for (int i = 0; i < n; i++)
		cin >> pre[i];
	turnpost(0, n - 1);//默认不是镜像转一次
	if (post.size() != n)//有可能是镜像
	{
		mir = true;
		post.clear();
		turnpost(0, n - 1);
	}
	if(post.size()==n)//已经转成功
	{
		cout << "YES" << endl << post[0];
		for (int i = 1; i < post.size(); i++)
			cout << " " << post[i];
	}
	else//一定不符合
		cout << "NO";
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值