题目要点:
解题的关键是理解题目所说的红黑的性质
There is a kind of balanced binary search tree named red-black tree in the data structure. It has the following 5 properties:
(1) Every node is either red or black.
(2) The root is black.
(3) Every leaf (NULL) is black.
(4) If a node is red, then both its children are black.
(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
从上面可以解读出:
是平衡二叉树,故可以根据前序遍历建立树
1.根节点是黑的,
2.红节点的左右孩子是黑的,
3.对于每个节点,从节点到子代叶子的所有简单路径都包含相同数量的黑色节点。(意思就是所有节点的左右子树的黑节点的数量相同)
#include<iostream>
#include<cmath>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
int k,n,pre[35];
struct Node{
int data;
Node *lchild,*rchild;
};
void indata(){//输入函数
for(int i=0;i<n;++i) cin>>pre[i];
};
Node * build(int pre[],int len){//建树
if(len==0) return NULL;
Node *root=new Node();
root->data=pre[0];
int i;
for(i=0;i<len;++i){
if(abs(pre[0])<abs(pre[i])) break;
}
root->lchild=build(&pre[1],i-1);
root->rchild=build(&pre[i],len-i);
return root;
}
bool flag3=true;
void judge2(Node *root){//红节点的孩子必须是黑的
if(root==NULL) return ;
judge2(root->lchild);
judge2(root->rchild);
if(root->data<0){
if(root->lchild&&root->lchild->data<0) flag3=false;
if(root->rchild&&root->rchild->data<0) flag3=false;
}
}
int judge3(Node *root){//左右子树相同
if(root->lchild==NULL&&root->rchild==NULL) {
if(root->data>0) return 1;
if(root->data<0) return 0;
}
int lcount=0,rcount=0;
if(root->lchild) lcount=judge3(root->lchild);
if(root->rchild) rcount=judge3(root->rchild);
return abs(lcount-rcount)+1;
}
bool judge(Node *root){
if(root->data<0) return false;//根
if(judge3(root)>1) return false;
flag3=true;
judge2(root);
if(flag3==false) return false;
return true;
}
int main(){
cin>>k;
while(k--){
cin>>n;
indata();
Node *root=build(pre,n);
if(judge(root)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}