2021天梯赛模拟L2-3这是二叉搜索树吗?
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 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
这道题的思路就是用递归的思想来进行后序遍历输出,先找左子树,再找右子树
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,pre[1010];
vector<int> post;
bool mirror=false;
void getpost(int root,int tail)
{
if(root>tail) return ;
int i=root+1;
int j=tail;
int root_data=pre[root];
if(!mirror)
{
while(pre[i]<root_data&&i<=tail) i++;
while(pre[j]>=root_data&&j>root) j--;
}
else//如果是镜像,只要相反一下就行
{
while(pre[i]>=root_data&&i<=tail) i++;
while(pre[j]<root_data&&j>root) j--;
}
if(i!=j+1) return ;
getpost(root+1,j);//找左子树
getpost(i,tail);//找右子树
post.push_back(root_data);
//cout<<root_data<<endl;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>pre[i];
}
getpost(0,n-1);
if(post.size()<n)//vector小于n说明可能是镜像,也可能都不是,后面再判断一次
{
post.clear();
mirror=true;
getpost(0,n-1);
}
if(post.size()<n) cout<<"NO";//既不是二叉搜索树,也不是镜像
else
{
cout<<"YES"<<endl;
cout<<post[0];
for(int i=1;i<n;i++)
{
cout<<" "<<post[i];
}
}
return 0;
}


浙公网安备 33010602011771号