PAT A1135 Is It A Red-Black Tree (30 分)
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 17
Sample Output:
Yes
No
No
思路:
这一开始眼看是红黑树,其实考察的只是二叉搜索树(BST)+条件判断的一道题目,题目中有用的条件判断是,要求一个二叉搜索树当满足以下条件时是一棵红黑树
1.根节点是黑色的
2.若某个结点是红色的,则其有孩子结点的话,孩子结点的颜色必须都是黑色
3.这棵树的每个结点到叶子结点路径上累计的黑色结点数必须相同,就是说A结点若有BC孩子结点,则BC到各自叶结点的路径中黑色结点数的总和必须相同
其他条件其实本题并没有用到是默认保证的
实现代码的方式就是基本的构建二叉搜索树,单独写一个递归判断来计算一个结点到达叶结点的路径中是否黑色结点数都是相等的,递归写法有两种,一种是逐层累加是从下往上计算的,一种是到达一个结点就从上往下递归计算,我采用的是第二种方式去计算该结点左右孩子到达叶子结点路径上所经历过的黑色结点总数。
代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct node {
int data;//负数代表红色结点
node *l,*r;
};
void insert(node *&root,int x) {
if(root==NULL) {
root=new node;
root->data=x;
root->l=root->r=NULL;
return;
}
if(abs(x)<abs(root->data)) insert(root->l,x);
else insert(root->r,x);
}
int blackCnt(node *root) {
if(root==NULL) return 0;
int L=blackCnt(root->l);
int R=blackCnt(root->r);
return max(L,R)+(root->data<0?0:1);//计算黑色结点数
}
bool judge(node *root) {
if(root==NULL) return true;
bool L=judge(root->l);
bool R=judge(root->r);
if(root->data<0) {//是红色结点
if(root->l&&root->l->data<0) return false;
if(root->r&&root->r->data<0) return false;
}
//统计左右孩子结点到达叶子结点路径上的黑色结点总数
if(blackCnt(root->l)!=blackCnt(root->r)) return false;
return L&&R;
}
int main() {
int n,m,val;
cin>>n;
while(n--) {
scanf("%d",&m);
node *root=NULL;
while(m--) {
scanf("%d",&val);
insert(root,val);
}
if(judge(root)&&root->data>=0) printf("Yes\n");
else cout<<"No\n";
}
return 0;
}

浙公网安备 33010602011771号