题意:
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;
}