Skip to content

Commit fa148d2

Browse files
count nodes of binary tree (#56)
1 parent 65ed1e3 commit fa148d2

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <assert.h>
4+
5+
typedef int ElemType;
6+
typedef struct Node {
7+
ElemType data;
8+
struct Node *left;
9+
struct Node *right;
10+
} Node;
11+
12+
/**
13+
* Create a new node with given data.
14+
* @param data the data store at node.
15+
* @return new node.
16+
*/
17+
Node *createNode(int data) {
18+
Node *newNode = (malloc(sizeof(Node)));
19+
newNode->data = data;
20+
return newNode;
21+
}
22+
23+
/**
24+
* Return the count of nodes of binary tree.
25+
* @param root the root node of binary tree.
26+
* @return the count of nodes of binary tree.
27+
*/
28+
int countNodes(Node *root) {
29+
return root == NULL ? 0 : 1 + countNodes(root->left) + countNodes(root->right);
30+
}
31+
32+
void test() {
33+
/* see images/example_binary_tree.png */
34+
Node *root = createNode(1);
35+
Node *node2 = createNode(2);
36+
Node *node3 = createNode(3);
37+
Node *node4 = createNode(4);
38+
Node *node5 = createNode(5);
39+
40+
root->left = node2;
41+
root->right = node3;
42+
43+
node2->left = node4;
44+
node2->right = node5;
45+
46+
node3->left = node3->right = NULL;
47+
node4->left = node4->right = NULL;
48+
node5->left = node5->right = NULL;
49+
50+
assert(countNodes(root) == 5);
51+
}
52+
53+
int main() {
54+
test();
55+
return 0;
56+
}

0 commit comments

Comments
 (0)