7-28 搜索树判断(25 分)

对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。
现在我们给出一个整数键值序列,请编写程序判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。

输入格式:

输入的第一行包含一个正整数 N(≤1000),第二行包含 N 个整数,为给出的整数键值序列,数字间以空格分隔。

输出格式:

输出的第一行首先给出判断结果,如果输入的序列是某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,则输出 YES,否侧输出 NO。如果判断结果是 YES,下一行输出对应二叉树的后序遍历序列。数字间以空格分隔,但行尾不能有多余的空格。

输入样例 1:

7
8 6 5 7 10 8 11

输出样例 1:

YES
5 7 6 8 11 10 8

输入样例 2:

7
8 6 8 5 10 9 11

输出样例 2:

NO

代码:

#include<vector>
#include<stdio.h>
using namespace std;
vector<int>tree;
int node,array[1024],i;
void positive(int father,int right){
	int treel=father+1,treer=right;
	while(treel<=right&&array[treel]<array[father])treel++;
	while(treer>father&&array[treer]>=array[father])treer--;
	if(treel-treer!=1)return;
	positive(father+1,treer);
	positive(treel,right);
	tree.push_back(array[father]);
}
void verso(int father,int right){
	int treel=father+1,treer=right;
	while(treel<=right&&array[treel]>=array[father])treel++;
	while(treer>father&&array[treer]<array[father])treer--;
	if(treel-treer!=1)return;
	verso(father+1,treer);
	verso(treel,right);
	tree.push_back(array[father]);
}
int main(){
	scanf("%d",&node);
	for(i=0;i<node;i++)scanf("%d",array+i);
	positive(0,node-1);
	if(tree.size()==node){
		printf("YES\n");
		for(i=0;i<node;i++){
			if(i)printf(" ");
			printf("%d",tree[i]);
		}
	}
	else{
		tree.empty();
		verso(0,node-1);
		if(tree.size()==node){
			printf("YES\n");
			for(i=0;i<node;i++){
				if(i)printf(" ");
				printf("%d",tree[i]);
			}
		}
		else printf("NO");
	}
	return 0;
}

提交结果:

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值