-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbintree_feature.c
executable file
·64 lines (58 loc) · 1.85 KB
/
bintree_feature.c
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
58
59
60
61
62
63
64
#include <stdio.h>
struct node{
int value;
struct node* pleft;
struct node* pright;
};
// count the depth of the binary tree
// the longest path(from the root to the leave node) length
int depth(struct node* root){
if(root == NULL)
return 0;
int left = depth(root->pleft);
int right = depth(root->pright);
return (left > right)?(left + 1):(right+1);
}
//judge balance binary tree
// one way to count the depth whether limit 1
int is_bbt(struct node* root){
if(root == NULL)
return 0;
int left = depth(root->pleft);
int right = depth(root->pright);
int diff = left - right;
if(diff > 1 || diff < -1)
return -1;
//return is_bbt(root->pleft) && is_bbt(root->pright);
return ( (is_bbt(root->pleft) == 0) && (is_bbt(root->pright) == 0) )?0:-1;
}
//another way use the last order in tree to according the child node depth decide the father node
int is_bbt_other(struct node* root, int* depth){
if(root == NULL){
*depth = 0 ;
return 0;
}
int left_depth ;
int right_depth;
if( (is_bbt_other(root->pleft,&left_depth) == 0) &&
(is_bbt_other(root->pright,&right_depth) == 0) ){
int diff = left_depth - right_depth;
if(diff <= 1 && diff >= -1){
//balanced
*depth = 1 + ((left_depth > right_depth)?left_depth:right_depth);
return 0;
}
}
return -1;
}
int is_balance(struct node* root){
int depth = 0;
int result = is_bbt_other(root,&depth);
return result;
}
int main(){
printf("%d\n",(-1)&&(-1));
printf("%d\n",(0)&&(0));
printf("%d\n",(-1)&&(0));
return 0;
}