题目
因为题目给的就是BST,所以直接按照BST的性质进行建树。需要满足红黑树的三个性质:一个是根结点为黑色,一个父结点为红色则子结点为黑色,一个相邻结点的路径中的黑色结点个数相同(个人认为,一个是比较兄弟结点,没有兄弟的就是最大值并记录,与其他无兄弟结点的叶子比较就行了)。以前不懂怎么写dfs的返回值不是void,这是第一次写,锻炼了。
#include <bits/stdc++.h>
using namespace std;
const int N=33;
int pre[N];
int k, n, res;
struct node{
int data;
node *lchild, *rchild;
};
node* newNode(int v){
node* Node = new node;
Node->data = v;
Node->lchild = Node->rchild = NULL;
return Node;
}
bool dfs(node* root, int num){
if(root==NULL){
if(!res)
res=num;
else if(res!=num)
return false;
return true;
}
if(root->data>0) {
if(dfs(root->lchild, num+1) && dfs(root->rchild, num+1))
return true;
else
return false;
} else {
if(root->lchild!=NULL && root->lchild->data<0)
return false;
if(root->rchild!=NULL && root->rchild->data<0)
return false;
if(dfs(root->lchild, num) && dfs(root->rchild, num))
return true;
else
return false;
}
}
void insert(node* &root, int data){
if(root == NULL){
root = newNode(data);
return;
}
if(abs(data) < abs(root->data))
insert(root->lchild, data);
if(abs(data)>abs(root->data))
insert(root->rchild, data);
}
node* create(){
node* root=NULL;
for(int i=0; i<n; i++)
insert(root, pre[i]);
return root;
}
int main()
{
scanf("%d", &k);
while(k--){
res = 0;
scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d", &pre[i]);
node* root=create();
if(!dfs(root, 0) || pre[0] < 0)
printf("No\n");
else
printf("Yes\n");
}
return 0;
}