浙大 PAT 甲级 1135 Is It A Red-Black Tree 红黑树的判断

#include<stdio.h>
#include<math.h>
#include<Windows.h>
#include<stdlib.h>
typedef struct Node* Tree;
struct Node
{
    int key;
    Tree left;
    Tree right;
    bool red;
};
int preorder[30];
Tree construct(int start, int end, bool &isRBT)
{
    if (start > end) return NULL;
    Tree T = (Tree)malloc(sizeof(Node));
    T->left = T->right = NULL;
    int key = preorder[start];
    if (key < 0)
    {
        T->key = -key;
        T->red = true;
    }
    else
    {
        T->key = key;
        T->red = false;
    }
    int index;
    for (index = start; index <= end; index++)
    {
        if (abs(preorder[index]) > abs(key))
        {
            break;
        }
    }
    T->left = construct(start + 1, index - 1, isRBT);
    T->right = construct(index, end, isRBT);
    if (T->red == true && ((T->left != NULL&&T->left->red == true) || (T->right != NULL&&T->right->red == true)))
    {
        isRBT = false;
    }
    return T;
}

int DFS(Tree T, bool &isRBT)
{
    if (T == NULL)
    {
        return 1;
    }
    int leftSum, rightSum;
    if (T->red == true)
    {
        leftSum = DFS(T->left, isRBT);
        rightSum = DFS(T->right, isRBT);
    }
    if (T->red == false)
    {
        leftSum = 1 + DFS(T->left, isRBT);
        rightSum = 1 + DFS(T->right, isRBT);
    }
    if (leftSum != rightSum)
    {
        isRBT = false;
        return -1;
    }
    else
    {
        return leftSum;
    }
}

int main()
{
    int K;
    scanf("%d", &K);
    for (int i = 0; i < K; i++)
    {
        // input
        int N;
        scanf("%d", &N);
        for (int j = 0; j < N; j++)
        {
            scanf("%d", &preorder[j]);
        }

        // construct a Tree
        bool isRBT = true;
        Tree T = construct(0, N - 1, isRBT);

        // judge it is a red-black tree
        // condition 1   The root is black.
        if (T->red == true)
        {
            printf("No\n");
            continue;
        }
        // condition 2  If a node is red, then both its children are black.
        if (isRBT == false)
        {
            printf("No\n");
            continue;
        }
        // condition 3   For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
        DFS(T, isRBT);
        if (isRBT == false)
        {
            printf("No\n");
        }
        else
        {
            printf("Yes\n");
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值