一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 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
#define x first
#define y second
#define send string::nops
using namespace std;
typedef long long ll;
const int N = 1e4 + 10;
const int M = 3 * N;
const int INF = 0x3f3f3f3f;
typedef pair PII;
typedef struct Node * pnode;
struct Node{
pnode left,right;
int val;
};
int a[N];
int flag1 = true,flag2 = true;
vectorres;
pnode build1(int l,int r){
pnode t = NULL;
if(l <= r){
t = (pnode)malloc(sizeof(Node));
t->val = a[l];
// cout<
int pox = l + 1;
while(a[pox] < a[l] && pox <= r)pox ++;
for(int i = pox;i <= r;i ++)
if(a[i] < a[l])
flag1 = false;
t->left = build1(l + 1,pox - 1);
t->right = build1(pox,r);
}
return t;
}
pnode build2(int l,int r){
pnode t = NULL;
if(l <= r){
t = (pnode)malloc(sizeof(Node));
t->val = a[l];
int pox = l + 1;
while(a[pox] >= a[l] && pox <= r)pox ++;
for(int i = pox;i <= r;i ++)
if(a[i] >= a[l])
flag2 = false;
t->left = build2(l + 1,pox - 1);
t->right = build2(pox,r);
}
return t;
}
void travel(pnode T){
if(T->left != NULL)
travel(T->left);
if(T->right != NULL)
travel(T->right);
res.push_back(T->val);
}
int main(){
int n;
cin>>n;
for(int i = 0;i < n;i ++)cin>>a[i];
pnode T = NULL;
T = build1(0,n - 1);
if(!flag1)
T = build2(0,n - 1);
if(flag1 || flag2){
cout<<"YES"<
travel(T);
cout<
for(int i = 1;i < res.size();i ++)cout<<" "<
}else cout<<"NO"<
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/139343.html