版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccDLlyy/article/details/79808366
题目链接:点击打开链接
思路:同PAT 甲级 1123 点击打开链接
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int root,data[25],le[25],rig[25];
void add(int &r,int loc){
if(r == -1){
r = loc;
return;
}
if(data[loc] > data[r]){
add(le[r],loc);
}
else{
add(rig[r],loc);
}
}
void inLevel(int r){
queue<int> q;
vector<int> v;
q.push(r);
while(!q.empty()){
int t = q.front();
q.pop();
v.push_back(t);
if(le[t] != -1) q.push(le[t]);
if(rig[t] != -1) q.push(rig[t]);
}
for(int i = 0;i < v.size();i++){
printf("%d%c",data[v[i]], i== v.size() - 1?'\n':' ');
}
return;
}
int judge(int r){
queue<int> q;
q.push(r);
while(!q.empty()){
int t = q.front();
q.pop();
if(t == -1) break;
q.push(le[t]);
q.push(rig[t]);
}
while(!q.empty()){
int t = q.front();
q.pop();
if(t != -1) return 0;
}
return 1;
}
int main(){
int n,num;
scanf("%d",&n);
root = -1;
memset(le,-1,sizeof(le));
memset(rig,-1,sizeof(rig));
for(int i = 1;i <= n;i++){
scanf("%d",&data[i]);
add(root,i);
}
inLevel(root);
int flag = judge(root);
puts(flag?"YES":"NO");
return 0;
}