您的位置:首页 > 理论基础 > 数据结构算法

ACM天梯赛 L2-004. 这是二叉搜索树吗?

2016-07-14 18:09 393 查看


L2-004. 这是二叉搜索树吗?

时间限制

400 ms

内存限制

65536 kB

代码长度限制

8000 B

判题程序

Standard

作者

陈越

一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,

其左子树中所有结点的键值小于该结点的键值;

其右子树中所有结点的键值大于等于该结点的键值;

其左右子树都是二叉搜索树。

所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。

输入格式:

输入的第一行给出正整数N(<=1000)。随后一行给出N个整数键值,其间以空格分隔。

输出格式:

如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出“YES”,然后在下一行输出该树后序遍历的结果。数字间有1个空格,一行的首尾不得有多余空格。若答案是否,则输出“NO”。
输入样例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

思路:根据先序遍历和二叉搜索树的特点建树。
由于该题存在镜像遍历,所以要先用个函数去判断是否是镜像遍历的。

代码加注释如下:

//https://www.patest.cn/contests/gplt/L2-004
//L2-004. 这是二叉搜索树吗?
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const int maxn=1010;
bool flag=true;
bool fist=false;
bool model=true;
struct tree_node
{
int value;
tree_node* leftchild;
tree_node* rightchild;
tree_node()
{
leftchild=NULL;
rightchild=NULL;
}
};
bool if_mirrortree(int a[],int length)//判断是否镜像树
{
if(a[1]>=a[0]&&a[length-1]<a[0])return true;
else if(a[1]<a[0]&&a[length-1]>=a[0])return false;
else if(a[1]>=a[0]&&a[length-1]>=a[0])
{
if(if_mirrortree(a+1,length-1))return true;
else return false;
}
return false;
}
tree_node* build_tree(int a[],int length)
{
if(length==0||!flag)return NULL;//终止条件
int pos=0;
bool pos_flag=false;//是否找到右子树
if(model)
{
for(int i=1;i<length;i++)
{
if(a[i]>=a[0]&&!pos_flag)//找到第一个比根大的数,该位置之后的都是右子树
{
pos=i;
pos_flag=true;
}
else if(pos_flag&&a[i]<a[0])//右子树中有比自己小的数。该树就不是二叉搜索树
{
flag=false;
break;
}
}
if(!pos_flag)pos=length;
}
else//镜像反之
{
for(int i=1;i<length;i++)
{
if(a[i]<a[0]&&!pos_flag)
{
pos=i;
pos_flag=true;
}
else if(pos_flag&&a[i]>=a[0])
{
flag=false;
break;
}
}
if(!pos_flag)pos=length;
}
if(!flag)return NULL;
tree_node* temp=new tree_node;
temp->value=a[0];
if(pos>0)temp->leftchild=build_tree(a+1,pos-1);
if(pos&&length-pos>0)temp->rightchild=build_tree(a+pos,length-pos);
return temp;
}
void dfs(tree_node* tree)
{
if(tree==NULL)return;
if(tree->leftchild!=NULL)
{
dfs(tree->leftchild);
}
if(tree->rightchild!=NULL)
{
dfs(tree->rightchild);
}
if(!fist)
{
cout<<tree->value;
fist=true;
}
else cout<<" "<<tree->value;
}
int main()
{
int n;
int a[maxn];
while(scanf("%d",&n)==1)
{
//initial
flag=true;
fist=false;
model=true;//镜像判断
//input
for(int i=0;i<n;i++)scanf("%d",&a[i]);
//solve
tree_node* tree;
if(if_mirrortree(a,n))model=false;
tree=build_tree(a,n);
if(flag)
{
cout<<"YES"<<endl;
dfs(tree);
cout<<endl;
}
else cout<<"NO"<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm