全ノードを、根から黒ノードの数を数えながら巡って、葉にたどり着いたら、黒接点の数を記録しておき、すでに記録した物と異なれば0
を返して終了し、全部のノードを巡り終わったら1
を返す。
再帰呼び出しで巡れば難しくない気がします。
#追記
黒の数には、根と葉も入れるとして、こんな感じでしょうか。
C
1##include <stdio.h>
2
3typedef struct node { struct node *left, *right; int black; } NODE;
4
5int count_save;
6
7int check(NODE *this, int count);
8
9int main(void){
10 NODE *root;
11 NODE x1, x2, x3, x4, x5, x6;
12
13 root = &x1;
14 x1 = (NODE){ &x2, &x3, 0 };
15 x2 = (NODE){ &x4, NULL, 1 };
16 x3 = (NODE){ &x5, &x6, 0 };
17 x4 = (NODE){ NULL, NULL, 0 };
18 x5 = (NODE){ NULL, NULL, 1 };
19 x6 = (NODE){ NULL, NULL, 1 };
20
21 count_save = -1;
22 printf("%d\n",check(root, 0));
23}
24
25int check(NODE *this, int count){
26 count += this->black;
27 if(!this->left && !this->right){ /* Leaf */
28 if(count_save==-1){
29 count_save = count;
30 return 1;
31 }else if(count_save != count){
32 return 0;
33 }else{
34 return 1;
35 }
36 }
37 if(this->left){
38 if(check(this->left,count)==0){
39 return 0;
40 }
41 }
42 if(this->right){
43 if(check(this->right,count)==0){
44 return 0;
45 }
46 }
47 return 1;
48}