题目传送门
(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.
一棵美丽的红黑树需要满足以下条件:
- 每一个结点不是红色就是黑色(这一点在题目中没有挖坑,即不会出现其他颜色的结点)
- 根结点是黑色
- 每一个叶结点(NULL)都是黑色的
- 如果一个结点是红色的,那么ta的两个孩子都是黑色的
- 对于任意一个结点,从ta到其子树内的叶结点,经过的黑色结点数量相同
题目给出了树的前序遍历
我一开始还在疑惑,只给出先序构造树岂不是有无穷多种情况嘛,难不成让我们构造出一种可行解吗
然而,红黑树是一种二叉搜索树,即
知道了这一点,我们就可以构造红黑树了
找到序列中第一个大于根结点的结点,即为右子树的开始结点
在构造好树后,我们dfs一遍判断其是否为红黑树
一开始我很不理解rule 3存在的意义,但是与rule 4结合起来看就明白了:
如果一个红色结点,左儿子(右儿子)是NULL,那么NULL被认为是黑色结点,满足rule 4
(3) Every leaf (NULL) is black.
(4) If a node is red, then both its children are black.
此外,还需要强调一个点
对于一个不是左右儿子双全的结点,我们认为NULL是一个黑色的叶结点
所以当遇到缺少儿子的结点时,我们需要检查rule 5
(3) Every leaf (NULL) is black.
(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
if (!(lc!=-1 && rc!=-1)) { //缺少儿子的结点
if (T_cnt == -1) T_cnt = cnt; //检测rule 5
else if (cnt != T_cnt) flag = 0;
}
AC代码
#include
#include
#include
#include
using namespace std;
const int N = 30;
int n;
int a[N + 1];
struct node {
int lc, rc;
int x;
int col;
};
node tree[N + 1];
int build(int s,int t) {
tree[s].x=abs(a[s]);
if (a[s] <= 0) tree[s].col = 0; //red
else tree[s].col = 1; //black
tree[s].lc = tree[s].rc = -1;
if (s == t) return s;
int m = s + 1;
while (abs(a[m]) <= abs(a[s]) && m <= n) m++; //right child
int left_sz = m - s - 1;
int right_sz = t - m + 1;
if (left_sz > 0)
tree[s].lc = build(s + 1, m - 1);
if (right_sz > 0)
tree[s].rc = build(m, t);
return s;
}
bool flag = 1;
int T_cnt;
void ss(int nw,int cnt) { //block nodes
int lc = tree[nw].lc;
int rc = tree[nw].rc;
if (!tree[nw].col) { //rule 3 & rule 4
if (lc != -1 && !tree[lc].col) {
flag = 0;
return;
}
if (rc != -1 && !tree[rc].col) {
flag = 0;
return;
}
}
if (!flag) return;
if (!(lc!=-1 && rc!=-1)) { //rule 3 & rule 5
if (T_cnt == -1) T_cnt = cnt;
else if (cnt != T_cnt) flag = 0;
}
if (!flag) return;
if (tree[nw].lc != -1 && flag)
ss(tree[nw].lc, cnt + tree[lc].col);
if (tree[nw].rc != -1 && flag)
ss(tree[nw].rc, cnt + tree[rc].col);
}
bool judge() {
flag = 1;
T_cnt = -1;
if (!tree[1].col) return 0; //rule 2
ss(1, 1);
return flag;
}
int main()
{
int T;
scanf("%d",&T);
while (T--) {
scanf("%d",&n);
for (int i = 1; i <= n; ++i) scanf("%d",&a[i]);
build(1, n);
if (!judge()) printf("No\n");
else printf("Yes\n");
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)