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.
For example, the tree in Figure 1 is a red-black tree, while the ones in Figure 2 and 3 are not.
|
|
|
|
|
|
For each given binary search tree, you are supposed to tell if it is a legal red-black tree.
Input Specification:
Each input file contains several test cases. The first line gives a positive integer K (<=30) which is the total number of cases. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the preorder traversal sequence of the tree. While all the keys in a tree are positive integers, we use negative signs to represent red nodes. All the numbers in a line are separated by a space. The sample input cases correspond to the trees shown in Figure 1, 2 and 3.
Output Specification:
For each test case, print in a line "Yes" if the given tree is a red-black tree, or "No" if not.
Sample Input:3 9 7 -2 1 5 -4 -11 8 14 -15 9 11 -2 1 -7 5 -4 8 14 -15 8 10 -7 5 -6 8 15 -11 17Sample Output:
Yes No No
补充一点小知识:
红黑树是二叉搜索树。
尤其是性质5,叶子结点是NIL结点,我一直以为是有两个NIL结点的父结点。。。。。。。性质1. 节点是红色或黑色。
性质2. 根是黑色。
性质3. 所有叶子都是黑色(叶子是NIL节点)。
性质4. 每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)
性质5. 从任一节点到其每个叶子的所有简单路径 都包含相同数目的黑色节点。
先根据前序遍历的结果构建二叉搜索树,然后对5个性质进行判断(其实只要判断2,4,5就可以了)。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
#include<queue>
#define MS(a,b) memset(a,b,sizeof(a))
typedef struct node
{
node *left,*right;
int data;
}*Tree;
int flag,num;
Tree T;
void insert1(Tree &T,int num)
{
if(T==NULL)
{
T=new node();
T->data=num;
T->left=NULL;
T->right=NULL;
return ;
}
if(abs(num)<=abs(T->data))insert1(T->left,num);
else insert1(T->right,num);
}
void dfs(Tree T,int cnt)
{
if(!flag)return ;//flag:为0表示不满足红黑树的条件。
if(T==NULL)
{
if(num==-1)num=cnt;//num:记录第一次到第一个叶子的黑色结点数目。
else if(num!=cnt)flag=0;
return ;
}
if(T->data>0)cnt++;
else
{
if(T->left!=NULL&&T->left->data<0)flag=0;
if(T->right!=NULL&&T->right->data<0)flag=0;
}
dfs(T->left,cnt);
dfs(T->right,cnt);
}
int main()
{
/* freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);*/
int t,n,pre[50],i,vis;
cin>>t;
while(t--)
{
cin>>n;
T=NULL;
for(i=1;i<=n;i++)
{
cin>>pre[i];
insert1(T,pre[i]);
}
if(pre[1]<0){cout<<"No\n";continue;}
flag=1;
num=-1;
dfs(T,0);
if( flag)
cout<<"Yes\n";
else cout<<"No\n";
}
return 0;
}