题意:给你一个二叉搜索树构建序列(负数代表红色节点,正数代表黑色节点),问建完之后该树是否是一颗红黑树。
需要了解红黑树的性质:
1.每个节点要么是红色要么是黑色
2.根节点为黑色
3.每个空结点(NULL)为黑色
4.每个红色节点的两个子节点为黑色(judge1)
5.从任一节点到其子树中每个叶子节点的路径都包含相同数量的黑色节点(judge2)
代码如下:
#include<bits/stdc++.h>
using namespace std;
struct node{
int val;
node *left;
node *right;
};
node* build(node* root,int val)
{
if(root==NULL)
{
root=new node();
root->val=val;
}
else if(abs(root->val)<abs(val))
{
root->right=build(root->right,val);
}
else
root->left=build(root->left,val);
return root;
}
bool judge1(node* root) //判断每个红色节点的儿子是否是黑色
{
if(root==NULL)
return true;
if(root->val<0)
{
if(root->left!=NULL && root->left->val<0)
return false;
if(root->right!=NULL && root->right->val<0)
return false;
}
return judge1(root->left) && judge1(root->right);
}
int getnum(node* root) //获取从当前点到叶子结点最大黑色节点数量
{
if(root==NULL)
return 0;
if(root->val>0) //若当前点为黑色节点,则+1
return max(getnum(root->left),getnum(root->right))+1;
return max(getnum(root->left),getnum(root->right));
}
bool judge2(node* root) //判断从每个节点左右子树黑色节点的最大数量是否相同。当所有节点左右子树最大黑色节点相同时,说明任意节点到叶子节点黑色节点数量相同
{
if(root==NULL)
return true;
int l=getnum(root->left); // 获取左子树到叶子结点黑色节点最大数量
int r=getnum(root->right); // 获取右子树到叶子结点黑色节点最大数量
if(l!=r)
return false;
return judge2(root->left) && judge2(root->right);
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,k;
cin>>n;
node* root=NULL;
for(int i=1;i<=n;i++)
{
cin>>k;
root=build(root,k);
}
if(root->val<0 || judge1(root)==false || judge2(root)==false)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
}