Home PAT 1135 Is It A Red-Black Tree
Post
Cancel

PAT 1135 Is It A Red-Black Tree

Link

注意是检查每个节点的左子树和右子树中黑色节点的个数是否相等.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <unordered_set>
using namespace std;
int k,n;
int pre[35];
struct node{
    int val;
    struct node *left,*right;
};
node* Insert(node *root,int val){
    if(root==NULL){
        root=new node();
        root->val=val;
        root->left=root->right=NULL;
    }else if(abs(val)<=abs(root->val)) root->left=Insert(root->left,val);
    else root->right=Insert(root->right,val);
    return root;
}
bool judge1(node *root){
    if(root==NULL) return true;
    if(root->val<0){
        if(root->left!=NULL&&root->left->val<0) return false;
        if(root->right!=NULL&&root->right->val<0) return false;
    }
    return judge1(root->left)&&judge1(root->right);
}
int getBlack(node *root){
    if(root==NULL) return 0;
    int l=getBlack(root->left),r=getBlack(root->right);
    return max(l,r)+(root->val>0?1:0);
}
bool judge2(node *root){
    if(root==NULL) return true;
    int l=getBlack(root->left),r=getBlack(root->right);
    if(l!=r) return false;
    return judge2(root->left)&&judge2(root->right);
}
int main() {
    scanf("%d",&k);
    while(k--){
        scanf("%d",&n);
        node *root=NULL;
        for(int i=1;i<=n;++i){
            scanf("%d",&pre[i]);
            root=Insert(root,pre[i]);
        }
        if(pre[1]<0||!judge1(root)||!judge2(root)) printf("No\n");
        else printf("Yes\n");
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.