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

 

#include<cstdio>
#include<vector>
#define maxn 33
#define inf 300
using namespace std;

struct simplenode {
    int d;
    bool red;
    simplenode(int _d, bool _red):d(_d), red(_red) {}
};

struct node {
    int d;
    bool red;
    node *left, *right;
};

node* buildtree(vector<simplenode> in, int sta, int en) {
    if (sta >= en) return NULL;
    int i;
    for (i = sta + 1; i < en; i++) {
        if (in[i].d >= in[sta].d) break;
    }
    node *root = new node;
    root->d = in[sta].d;
    root->red = in[sta].red;
    root->left = buildtree(in, sta + 1, i);
    root->right = buildtree(in, i, en);
    return root;
}

// return the num of the black nodes the tree base on "root" have,
// while checking it is valid
int check_black_num (node *root) {
    if (root == NULL) return 1;

    int left = check_black_num(root->left);
    if (left >= inf) return inf;
    int right = check_black_num(root->right);
    if (right >= inf) return inf;
    if (left != right) return inf;

    if (root->red == false) return left + 1;
    else return left;
}

bool check_children_red(node *root) {
    if (root == NULL) return true;
    if (root->red == true) {
        if (root->left != NULL && root->left->red == true) return false;
        if (root->right != NULL && root->right->red == true) return false;
    }
    if (root->left != NULL && check_children_red(root->left) == false) return false;
    if (root->right != NULL && check_children_red(root->right) == false) return false;
    return true;
}

bool check_red_black(node *root) {
    if (root->red == true) return false;
    if (check_children_red(root) == false) return false;
    int left = check_black_num(root->left);
    if (left >= inf) return false;
    int right = check_black_num(root->right);
    if (right >= inf) return false;
    if (left != right) return false;
    return true;
}

int main() {
    int K, N, a;
    scanf("%d", &K);
    while(K--) {
        scanf("%d", &N);
        vector<simplenode> input;
        for (int i = 0; i < N; i++) {
            scanf("%d", &a);
            if (a < 0) {
                input.push_back(simplenode(-a, true));
            }
            else input.push_back(simplenode(a, false));
        }
        node *root = buildtree(input, 0, N);
        if (check_red_black(root)) printf("Yes\n");
        else printf("No\n");

    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值