https://pintia.cn/problem-sets/994805342720868352/problems/994805346063728640
本质上是DFS题
注意红黑树是二叉搜索树
#include <iostream>
#include <algorithm>
using namespace std;
const int SIZE = 10005;
struct Node {
int data;
int redOrBlack; //red是0,black是1
Node* left,* right;
Node() {left = right = NULL;}
} ;
int preOrder[SIZE];
void createTree(Node*& root, int left, int right) {
if (left > right) return;
if (root == NULL) {
root = new Node();
root->data = abs(preOrder[left]);
if (preOrder[left] < 0) root->redOrBlack = 0;
else root->redOrBlack = 1;
}
int mid;
for (mid = left + 1; mid <= right; mid ++) {
if (abs(preOrder[mid]) > abs(preOrder[left])) break;
}
createTree(root->left, left + 1, mid - 1);
createTree(root->right, mid, right);
}
bool flag = true;
int blackSum = 0;
void DFS(Node* root, int bSum) {
if (root == NULL) {
if (bSum != blackSum) flag = false; //黑节点的数量不同
return ;
}
if (root->redOrBlack == 0 && root->left != NULL && root->right != NULL) {
if (root->left->redOrBlack == 0 || root->right->redOrBlack == 0) flag = false; //红节点的左右节点存在不是黑色的节点
}
if (root->left != NULL && root->left->redOrBlack == 1) DFS(root->left, bSum + 1);
else DFS(root->left, bSum);
if (root->right != NULL && root->right->redOrBlack == 1) DFS(root->right, bSum + 1);
else DFS(root->right, bSum);
}
void DFSTree(Node* root) {
DFS(root, 1);
}
int main() {
int K, N;
cin >> K;
while (K --) {
flag = true;
blackSum = 0;
cin >> N;
for (int i = 0; i < N; i ++) cin >> preOrder[i];
Node* root = NULL;
createTree(root, 0, N - 1);
Node* troot = root;
while (troot != NULL) { //计算出一条路径上的黑节点数量
if (troot->redOrBlack == 1) blackSum ++;
troot = troot->left;
}
DFSTree(root);
if (flag) cout << "Yes" << endl;
else cout << "No" << endl;
}
cin >> N;
return 0;
}