判断所给的🌲是否是红黑树,本题考察了红黑树的定义
坑点如下
红黑树的判据
1,根结点一定是黑
2,当前结点为红,其两个孩子结点一定是黑
3,任意一个结点到其所有根结点的路径含有相同的黑结点个数(判断方式)
4,注意判断代码的写法
从根结点依次判断左右结点。
bool judge1(node* root){
if(root==NULL)return true;
if(root->data<0)
{ if(root->lchild!=NULL&&root->lchild->data<0)return false;
if(root->rchild!=NULL&&root->rchild->data<0)return false;}
return judge1(root->lchild)&&judge1(root->rchild);
}
bool judge2(node* root){
if(root==NULL)return true;
int l=getnum(root->lchild);
int r=getnum(root->rchild);
if(l!=r)return false;
return judge2(root->lchild)&&judge2(root->rchild);
}
整体代码如下
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
int h;
};
void insert(node* &root,int data){
if(root==NULL){
root=new node;
root->lchild=root->rchild=NULL;
root->data=data;
return;}
if(abs(data)>=abs(root->data))insert(root->rchild,data);
else insert(root->lchild,data);
}
bool judge1(node* root){
if(root==NULL)return true;
if(root->data<0)
{ if(root->lchild!=NULL&&root->lchild->data<0)return false;
if(root->rchild!=NULL&&root->rchild->data<0)return false;}
return judge1(root->lchild)&&judge1(root->rchild);
}
int getnum(node* root){
if(root==NULL)return 1;
int l=getnum(root->lchild);
int r=getnum(root->rchild);
return root->data>0?max(l,r)+1:max(l,r);
}
bool judge2(node* root){
if(root==NULL)return true;
int l=getnum(root->lchild);
int r=getnum(root->rchild);
if(l!=r)return false;
return judge2(root->lchild)&&judge2(root->rchild);
}
int main(){
int k,n,d;
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d",&n);
node* root=NULL;
for(int l=0;l<n;l++){
scanf("%d",&d);
insert(root,d);
}
if(root->data>0&&judge1(root)&&judge2(root))
{printf("Yes\n");}
else printf("No\n");
}
return 0;
}