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

题目链接
在这里插入图片描述
绝对的菜鸡了,看到二叉树只会先递归重建。。。搞了半天过一个样例,15分。哭了。只好去看看柳神的题解
学习了学习了。

代码

#include <iostream>
#include <vector>
#include <cstdio>
#include <cmath>
using namespace std;
int K;
struct Node
{
    int val;
    Node* lc,*rc;
};
Node* build(Node* root,int val)
{
    if(root==NULL)
    {
        root = new Node();
        root->val = val;
        root->lc = NULL;
        root->rc = NULL;
        return root;
    }
    else if(abs(val)<=abs(root->val))
        root->lc = build(root->lc,val);
    else root->rc = build(root->rc,val);
    return root;
}
bool judgeblk(Node* root)
{
    if(root==NULL)
        return true;
    if(root->val<0)
    {
        if(root->lc&&root->lc->val<0)
            return false;
        if(root->rc&&root->rc->val<0)
            return false;
    }
    return judgeblk(root->lc)&&judgeblk(root->rc);
}
int getblkNum(Node* root)
{
    if(root==NULL)
        return 0;
    int lc = getblkNum(root->lc);
    int rc = getblkNum(root->rc);
    return root->val > 0 ? max(lc,rc)+1:max(lc,rc); 
}
bool judgeblkNum(Node* root)
{
    if(root==NULL)
        return true;
    int lnum = getblkNum(root->lc);
    int rnum = getblkNum(root->rc);
    if(lnum!=rnum)
        return false;
    return judgeblkNum(root->lc) && judgeblkNum(root->rc);
}
int main()
{
    scanf("%d",&K);
    while(K--)
    {
        int N;
        scanf("%d",&N);
        vector<int> pre;
        pre.resize(N);
        Node* root = NULL;
        for(int i=0;i<N;i++)
        {
            scanf("%d",&pre[i]);
            root = build(root,pre[i]);
        }
        if(pre[0]<0||!judgeblk(root)||!judgeblkNum(root))
            printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值