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

审题:红黑树是二叉树,所以可以直接根据先序建树(注意小于等于放在一起)
每一个节点到叶子结点的黑色的数目要相同

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node {
    int data;
    node *lchild, *rchild;
};
void insert(node*&root, int x)
{
    if (root == NULL)
    {
        root = new node;
        root->data = x;
        root->lchild = root->rchild = NULL;
        return;
    }
    if (abs(x) <= abs(root->data))insert(root->lchild, x);
    else insert(root->rchild, x);
}
bool judge1(node* root)
{
    if (root == NULL)return true;
    if (root->data < 0)
    {
        if (root->lchild&&root->lchild->data < 0)return false;
        if (root->rchild&&root->rchild->data < 0)return false;
    }
    return judge1(root->lchild) && judge1(root->rchild);
}
int getheight(node* root)
{
    if (root == NULL)return 0;
    int l = getheight(root->lchild);
    int r = getheight(root->rchild);
    return root->data > 0 ? max(l, r) + 1 : max(l, r);
}
bool judge2(node* root)
{
    if (root == NULL)return true;
    int l = getheight(root->lchild);
    int r = getheight(root->rchild);
    if (l != r)return false;
    return judge2(root->lchild) && judge2(root->rchild);
}
int k, n;
vector<int>a;
int main()
{
    scanf("%d", &k);
    while (k--)
    {
        node* root = NULL;
        scanf("%d", &n);
        a.resize(n);
        bool f = true;
        for(int i=0;i<n;i++)
        {
            scanf("%d", &a[i]);
            insert(root, a[i]);
        }
        if (a[0] < 0 || judge1(root) == false || judge2(root) == false)printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • B树的定义 一棵m阶的B树满足下列条件: 树中每个结点至多有m个孩子。 除根结点和叶子结点外,其它每个结点至少有m...
    文档随手记阅读 13,661评论 0 25
  • 一些概念 数据结构就是研究数据的逻辑结构和物理结构以及它们之间相互关系,并对这种结构定义相应的运算,而且确保经过这...
    Winterfell_Z阅读 6,577评论 0 13
  • 目录 0.树0.1 一般树的定义0.2 二叉树的定义 1.查找树ADT 2.查找树的实现2.1 二叉查找树2.2 ...
    王侦阅读 7,557评论 0 3
  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 4,756评论 1 31
  • 一.dispatch_barrier_async 栅栏块 在一个自定义的并行队列中执行多个任务block时,如果接...
    小赢一场阅读 599评论 0 1

友情链接更多精彩内容