原题目参见1135 Is It A Red-Black Tree (30分),要求判断一个树的先根序列
是否能构成红黑树。由于红黑树是搜索二叉树,所以给定一个先根序列,可以唯一生成一棵搜索二叉树,如果无法生成搜索二叉树,则判否。再由题目给的红黑树的生成条件,判断该序列是否为合法的红黑树。
(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.
下面是AC代码(C++版本)。
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 50;
struct Node {
int data, color, bd; // a[l]>0,1表示黑树,0表示红树。
Node* lchild, * rchild;
void print() {
printf("data = %d. color = %d. \n", data, color);
}
};
int a[maxn], b[maxn]; //a: original data. b: positive data.
bool bstf, brtf; // binary search tree flag, black red tree flag.
Node* createNode(int data, int color) {
Node* root = new Node;
root->data = data;
root->lchild = NULL;
root->rchild = NULL;
root->color = color;
return root;
}
// Use b[] to create a binary search tree.
int createTree(int l, int r, Node*& root) {
if (l == r) {
root = createNode(b[l], a[l]>0);
return 0;
}
int rootd = b[l];
int rid = l+1;
root = createNode(b[l], a[l]>0);
for (; rid <= r; rid++) {
if (b[rid] > rootd) {
break; //找到第一个比根节点大的节点。在该节点的右侧应该所有的节点都比根节点小。
}
}
for (int testid = rid; testid <= r; testid++) {
if (b[testid] < rootd) {
bstf = 0;//不符合二叉查找树的先根遍历序列要求。
return 0;
}
}
if (rid != l + 1) {
//有左子树。
createTree(l + 1, rid - 1, root->lchild);
}
if (rid != r + 1) {
//有右子树。
createTree(rid, r, root->rchild);
}
return 1;
}
int getBNum(Node* root) {
int l = (root->lchild == NULL || (root->lchild && root->lchild->color));
int r = (root->rchild == NULL || (root->rchild && root->rchild->color));
return l + r;
}
int judgeBRT(Node* root) {
if (root == NULL) {
return 1;
}
int lbn = judgeBRT(root->lchild);
int rbn = judgeBRT(root->rchild);
if (lbn != rbn || (!root->color&&getBNum(root)<2)) {
brtf = 0;
}
return lbn+root->color;
}
int main()
{
int k, n, t;
scanf("%d", &k);
for (int i = 0; i < k; i++) {
scanf("%d", &n);
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
bstf = 1;
brtf = 1;
Node* root = NULL;
for (int j = 0; j < n; j++) {
scanf("%d", &a[j]);
b[j] = abs(a[j]);
}
if (a[0] > 0) {
createTree(0, n - 1, root);
if (bstf) {
judgeBRT(root);
if (brtf) {
printf("Yes\n");
}
else {
printf("No\n");
}
}
else {
printf("No\n");
}
}
else {
printf("No\n");
}
}
return 0;
}