1135 Is It A Red-Black Tree (30分)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值