PAT题目目录
红黑树
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
unordered_map<int,int> pos;
bool ans;
const int N=40;
int pre[N],in[N];
int build(int il,int ir,int pl,int pr,int &sum){
int root=pre[pl];
int k=pos[abs(root)];
if(k<il||k>ir){ans=false;return 0;}
int left_root=0,right_root=0,left_sum=0,right_sum=0;
if(k>il) left_root=build(il,k-1,pl+1,pl+1+k-1-il,left_sum);
if(k<ir) right_root=build(k+1,ir,pl+1+k-1-il+1,pr,right_sum);
if(left_sum!=right_sum) ans=false;
sum=left_sum;
if(root<0){
if(left_root<0||right_root<0) ans=false;
}
else sum++;
return root;
}
int main(){
int K;cin>>K;
while(K--){
int n;cin>>n;
for(int i=0;i<n;i++){
cin>>pre[i];in[i]=abs(pre[i]);
}
sort(in,in+n);
pos.clear();
for(int i=0;i<n;i++) pos[in[i]]=i;
int sum=0;
ans=true;
int root=build(0,n-1,0,n-1,sum);
if(root<0) ans=false;
if(ans) puts("Yes");
else puts("No");
}
return 0;
}