码迷,mamicode.com
首页 > 其他好文 > 详细

PAT A1135 Is It A Red Black Tree

时间:2020-02-13 00:16:37      阅读:37      评论:0      收藏:0      [点我收藏+]

标签:main   printf   判断   oid   bit   ack   红黑树   void   tree   

判断一棵树是否是红黑树,按题给条件建树,dfs判断即可~

#include<bits/stdc++.h>
using namespace std;
const int maxn=1010;
struct node {
    int data;
    node * left=NULL;
    node * right=NULL;
};
void insert (node * &root,int x) {
    if (root==NULL) {
        root=new node;
        root->data=x;
        return;    
    }
    if (abs(x)<abs(root->data)) insert (root->left,x);
    else insert (root->right,x);
}
int getnum (node * root) {
    if (root==NULL) return 1;
    if (root->data>0)
    return max(getnum(root->left),getnum(root->right))+1;
    else return max(getnum(root->left),getnum(root->right));
}
int flag=0;
void dfs (node * root) {
    if (root==NULL) return;
    if (root->data<0&&root->left&&root->left->data<0) flag++;
    if (root->data<0&&root->right&&root->right->data<0) flag++;
    if (getnum(root->left)!=getnum(root->right)) flag++;
    dfs (root->left);
    dfs (root->right);
}
int main () {
    int T;
    scanf ("%d",&T);
    int N,x;
    while (T--) {
        node * root=NULL;
        scanf ("%d",&N);
        for (int i=0;i<N;i++) {
            scanf ("%d",&x);
            insert (root,x);
        }
        flag=0;
        if (root->data<0) flag++;
        dfs (root);
        if (flag==0) printf ("Yes\n");
        else printf ("No\n");
    }
    return 0;
}

 

PAT A1135 Is It A Red Black Tree

标签:main   printf   判断   oid   bit   ack   红黑树   void   tree   

原文地址:https://www.cnblogs.com/zhanglichen/p/12301701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!