1135 Is It A Red-Black Tree

#include<iostream>
#include<vector>
#include<map>
#include<bits/stdc++.h>
using namespace std;
map<int,int> mp;
vector<int> pre,in;
struct node{
	int value;
	node* left;
	node* right;
};
node* build(int prel,int prer,int inl,int inr){
	if(prel>prer) return 0;
	node* root=new node;
	root->value=pre[prel];
	root->left=NULL;
	root->right=NULL;
	int k;
	for(k=inl;k<=inr;k++){
		if(pre[prel]==in[k]){
			break;
		}
	}
	int numleft=k-inl;
	root->left=build(prel+1,prel+numleft,inl,k-1);
	root->right=build(prel+numleft+1,prer,k+1,inr);
	return root;
}
bool judge1(node* root){
	if(root==NULL) return true;
	if(mp[root->value]==-1){
		if(root->left!=NULL&&mp[root->left->value]==-1) return false;
		if(root->right!=NULL&&mp[root->right->value]==-1) return false;
	}
	return judge1(root->left)&&judge1(root->right);
}
int getNum(node *root) {
    if (root == NULL) return 0;
    int l = getNum(root->left);
    int r = getNum(root->right);
    return mp[root->value] > 0 ? max(l, r) + 1 : max(l, r);
}
bool judge2(node *root) {
    if (root == NULL) return true;
    int l = getNum(root->left);
    int r = getNum(root->right);
    if(l != r) return false;
    return judge2(root->left) && judge2(root->right);
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt","r",stdin);
	#endif
	int k;
	cin>>k;
	for(int i=0;i<k;i++){
		int n;
		cin>>n;
		for(int j=0;j<n;j++){
			int temp=0;
			cin>>temp;
			if(temp>0){
				in.push_back(temp);
				pre.push_back(temp);mp[temp]=1;
			}else{
				temp=abs(temp);
				pre.push_back(temp);in.push_back(temp);mp[temp]=-1;
			}
		}
		sort(in.begin(),in.end());
		node* root;
		root=build(0,n-1,0,n-1);
		//cout<<root->right->value<<endl; 
		if(mp[pre[0]]==-1){
			cout<<"No"<<endl;
		}else if(!judge1(root)){
			cout<<"No"<<endl;
		}else if(!judge2(root)){
			cout<<"No"<<endl;	
		}else{
			cout<<"Yes"<<endl;
		}
		pre.clear();
		in.clear();
		mp.clear();
	}
	return 0;
}



猜你喜欢

转载自blog.csdn.net/csg3140100993/article/details/81392692