File tree 2 files changed +69
-1
lines changed
2 files changed +69
-1
lines changed Original file line number Diff line number Diff line change @@ -23,7 +23,7 @@ Compile **C++** files using command:
23
23
| 225 | [ Implement Stack using Queues] | [ C] ( src/225.c ) |
24
24
| 224 | [ Basic Calculator] | [ C] ( src/224.c ) |
25
25
| 223 | [ Rectangle Area] | [ C] ( src/223.c ) |
26
- | 222 | [ Count Complete Tree Nodes] | |
26
+ | 222 | [ Count Complete Tree Nodes] | [ C ] ( src/222.c ) |
27
27
| 221 | [ Maximal Square] | |
28
28
| 220 | [ Contains Duplicate III] | |
29
29
| 219 | [ Contains Duplicate II] | |
Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+
4
+ struct TreeNode {
5
+ int val ;
6
+ struct TreeNode * left ;
7
+ struct TreeNode * right ;
8
+ };
9
+
10
+ int countNodes (struct TreeNode * root ) {
11
+ if (root == NULL ) return 0 ;
12
+
13
+ struct TreeNode * l = root -> left ;
14
+ struct TreeNode * r = root -> right ;
15
+
16
+ int most_left_height = 1 ;
17
+ int most_right_height = 1 ;
18
+
19
+ while (l != NULL ) {
20
+ l = l -> left ;
21
+ most_left_height ++ ;
22
+ }
23
+
24
+ while (r != NULL ) {
25
+ r = r -> right ;
26
+ most_right_height ++ ;
27
+ }
28
+
29
+ if (most_left_height == most_right_height ) { /* it's a full binary tree */
30
+ return (1 << most_left_height ) - 1 ;
31
+ }
32
+ else {
33
+ return countNodes (root -> left ) + countNodes (root -> right ) + 1 ;
34
+ }
35
+ }
36
+
37
+ int main () {
38
+
39
+ struct TreeNode * r = (struct TreeNode * )calloc (9 , sizeof (struct TreeNode ));
40
+ struct TreeNode * p = r ;
41
+
42
+ int i ;
43
+ for (i = 1 ; i <= 9 ; i ++ ) {
44
+ p -> val = i ;
45
+ p ++ ;
46
+ }
47
+
48
+ p = r ;
49
+ p -> left = r + 1 ;
50
+ p -> right = r + 2 ;
51
+
52
+ p = r + 1 ;
53
+ p -> left = r + 3 ;
54
+ p -> right = r + 4 ;
55
+
56
+ p = r + 2 ;
57
+ p -> left = r + 5 ;
58
+ p -> right = r + 6 ;
59
+
60
+ p = r + 3 ;
61
+ p -> left = r + 7 ;
62
+ p -> right = r + 8 ;
63
+
64
+ /* should be 9 */
65
+ printf ("%d\n" , countNodes (r ));
66
+
67
+ return 0 ;
68
+ }
You can’t perform that action at this time.
0 commit comments