题目大意:给出红黑树满足的5个性质,然后给出先序序列,判断是否是红黑树。
题目给出的红黑树的5个性质如下:
- (1) Every node is either red or black. 每个节点要么是红色,要么是黑色。
- (2) The root is black. 根节点是黑色。
- (3) Every leaf (NULL) is black. 每个叶子节点(即NULL节点)是黑色。
- (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. 对每个节点而言,到达它的每个叶子节点的简单路径上,经过的黑色节点总数是一致的。
这5个性质里,第3个和第5个我一时没看懂,还是wiki了一下才明白的。红黑树的定义里,叶子节点是NULL节点,而不是通常所说的左右孩子为空的节点是NULL节点,也就是说每个左右孩子为空的节点,实际上左右孩子都是叶子节点。然后,性质5是说每个节点到达叶子节点(NULL)节点的简单路径上经过的黑色节点总数相等。
因为红黑树也是BST,满足中序序列有序,然后根据先序和中序序列构建树。之后就是要检验这棵树是否满足5个性质,性质2 3 4都容易检验,问题在于性质5。考虑到题目的数据量不会很大(一棵树最多30个节点),就直接暴力地遍历每个节点,在访问到某个节点时,依次检验是否满足5个性质。检验性质5的方法是:将每个节点能到达的叶子节点的路径上经过的黑色节点的数目存储下来,比较这些数是否相等就好了。遍历的方式是选择层序遍历。记录的方法是DFS, 递归结束的条件是节点为空(即叶子节点)。
AC代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstring>
using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
Node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
void createFromPreIn(Node*& node, vector<int> &pre, vector<int> &in, int prel, int prer, int inl, int inr)
{
if(prel > prer) return;
if(node == NULL) node = new Node(pre[prel]);
int i;
for (i = inl; i <= inr; ++i)
{
if(in[i] == abs(node->data)) break;
}
int leftNum = i - inl;
createFromPreIn(node->left, pre, in, prel+1, prel+leftNum, inl, i-1);
createFromPreIn(node->right, pre, in, prel+leftNum+1, prer, i+1, inr);
}
void blackNodesCount(Node* node, vector<int> &v, int count)
{
if(node == NULL)
{
v.push_back(count);
return;
}
if(node->data > 0)
{
blackNodesCount(node->left, v, count+1);
blackNodesCount(node->right, v, count+1);
}
else
{
blackNodesCount(node->left, v, count);
blackNodesCount(node->right, v, count);
}
}
bool layerOrder(Node* node)
{
if(node->data < 0) return false;
queue<Node*> q;
q.push(node);
while(!q.empty())
{
Node* now = q.front();
q.pop();
if(now->data < 0)
{
if(now->left != NULL && now->left->data < 0) return false;
if(now->right != NULL && now->right->data < 0) return false;
}
vector<int> v;
blackNodesCount(now, v, 0);
for (int i = 1; i < v.size(); ++i)
{
if(v[i] != v[i-1]) return false;
}
if(now->left != NULL) q.push(now->left);
if(now->right != NULL) q.push(now->right);
}
return true;
}
int main()
{
int K;
cin >> K;
for (int query = 0; query < K; ++query)
{
int N;
cin >> N;
vector<int> pre(N), in(N);
for (int i = 0; i < N; ++i)
{
scanf("%d", &pre[i]);
in[i] = abs(pre[i]);
}
sort(in.begin(), in.end());
Node* root = NULL;
createFromPreIn(root, pre, in, 0, N-1, 0, N-1);
bool isRBT = layerOrder(root);
if(isRBT) printf("Yes\n");
else printf("No\n");
}
return 0;
}