#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node* TreeNode;
struct Node{ //creat a linked list
int data; //the value of the node
TreeNode right,left; //two children of the node
};
int maxnumber(int m,int n){ //creat a function to choose the maximum
if(m>=n)
return m;
else
return n;
}
TreeNode insert(TreeNode t,int x){ //add a new number to the tree
if(t==NULL){ //when tree has nothing, the number will the root
t=(TreeNode)malloc(sizeof(struct Node));
t->data=x;
t->left=NULL;
t->right=NULL;
}
else if(abs(x)<abs(t->data)) //add the smaller to the left
t->left=insert(t->left,x);
else //add the bigger to the right
t->right=insert(t->right, x);
return t;
}
int Judge_Two_Linked_Red(TreeNode t){ //the function can judge whether the tree has two linked red nodes
int samp=1;
if(t->left!=NULL){ //check the left side
if(t->data<0 && t->left->data<0)
return 0; //find it. the tree has an error.
else
samp*=Judge_Two_Linked_Red(t->left);
}
if(t->right!=NULL){ //check the right side
if(t->data<0 && t->right->data<0)
return 0; //find it. the tree has an error.
else
samp*=Judge_Two_Linked_Red(t->right);
}
return samp; //not find error
}
int Count_Black(TreeNode t){ //the function can count the black number from one node to its leaf
if(t==NULL)
return 0; //zero black node.
int left_count=0,right_count=0;
left_count=Count_Black(t->left);
right_count=Count_Black(t->right);
if(t->data>0)
return maxnumber(left_count,right_count)+1;
else
return maxnumber(left_count,right_count);
}
int Judge_Different_Black_Nodes(TreeNode t){//the function can judge whether the node has same number of black nodes in the way to each leaf
if(t==NULL)
return 1; //not find
int left_count=Count_Black(t->left);
int right_count=Count_Black(t->right);
if(left_count!=right_count)
return 0; //find it. the tree has an error.
return Judge_Different_Black_Nodes(t->left)*Judge_Different_Black_Nodes(t->right);
}
int main(){
int K,N,x;
int i,j;
TreeNode a=NULL;
scanf("%d",&K); //get K
for(i=0;i<K;i++){
int flag=1;
scanf("%d",&N); //get N
a=NULL;
for(j=0;j<N;j++){
scanf("%d",&x);
a=insert(a,x); //build the tree
}
if(a->data<0){ //if the root is red, the tree has an error.Wrong!
printf("No\n");
}
else{
flag=Judge_Two_Linked_Red(a);
// if(a->left==NULL)
if(flag==0){
printf("No\n"); //the tree has linked red nodes. Wrong!
}
else{
flag=Judge_Different_Black_Nodes(a);
if(flag==0){
printf("No\n"); //the tree has different numbesr of black nodes from one node to its leaf. Wrong!
}
else printf("Yes\n"); //Nothing is wrong.
}
}
}
}
1
最新推荐文章于 2024-08-24 08:00:00 发布