1135 Is It A Red-Black Tree (30 分)

判断所给的🌲是否是红黑树,本题考察了红黑树的定义
坑点如下
红黑树的判据
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值