PATA1135题解

题意:

1、每个节点非红即黑

2、根节点为黑

3、每个叶节点均为黑(判断数量时可以忽略这个条件)

4、如果一个节点为红,则它的孩子节点为黑色

5、对于每个节点,从该节点出发到任何一个它的子孙叶节点所包含的黑色节点数相同


//
//  main.cpp
//  PATA1135
//
//  Created by Phoenix on 2018/2/26.
//  Copyright © 2018年 Phoenix. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
bool flag1, flag2, flag3;
struct Node {
    int color;          //0表示红色节点,1表示黑色节点
    int data;
    int height;         //记录该节点到叶节点黑色节点的数量
    Node *lchild, *rchild;
};

Node* newnode(int x) {
    Node* root = new Node;
    root->data = abs(x);
    if(x < 0) root->color = 0;      //标记颜色
    else root->color = 1;
    root->lchild = root->rchild = NULL;
    return root;
}

void insert(Node* &root, int x) {       //构造红黑树
    if(root == NULL) {
        root = newnode(x);
        return;
    }
    if(root->data > abs(x)) insert(root->lchild, x);
    else insert(root->rchild, x);
}

void postorder(Node* root) {        //通过后序遍历用 flag2来判断红节点的左右孩子节点是否为黑,flag3判断每个节点的左右孩子的黑高是否相同
    if(root == NULL) return;
    postorder(root->lchild);
    postorder(root->rchild);
    if(root->color == 0) {          //如果该节点为红色节点,左右孩子存在的话判断是否为黑
        if(root->lchild && root->lchild->color == 0) flag2 = false;
        if(root->rchild && root->rchild->color == 0) flag2 = false;
    }
    if(root->lchild == NULL && root->rchild == NULL) {      //如果节点为叶节点,初始化该节点的黑色数量
        root->height = root->color;
    } else if(root->lchild != NULL && root->rchild != NULL){    //如果节点有左右孩子,判断左右孩子的黑色数量是否相同
        if(root->lchild->height != root->rchild->height) flag3 = false;
        else root->height = root->lchild->height + root->color;
    } else {        //如果只有一个孩子节点,判断这个孩子节点的黑色数量是否为0
        if(root->lchild == NULL) {
            if(root->rchild->height != 0) flag3 = false;
            else root->height = root->color;
        }
        if(root->rchild == NULL) {
            if(root->lchild->height != 0) flag3 = false;
            else root->height = root->color;
        }
    }
}



int main(int argc, const char * argv[]) {
    int k, n;
    scanf("%d", &k);
    for(int i = 0; i < k; i++) {
        scanf("%d", &n);
        Node* root = NULL;
        flag1 = flag2 = flag3 = true;
        for(int j = 0; j < n; j++) {
            int a;
            scanf("%d", &a);
            insert(root, a);
        }
        if(root->color == 0) flag1 = false;     //判断根节点是否为黑
        postorder(root);
        if(flag1 && flag2 && flag3) 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、付费专栏及课程。

余额充值