File tree 1 file changed +57
-0
lines changed
datastructures/binarytree
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
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
+ int depth (Node * root ) {
24
+ if (root == NULL ) {
25
+ return 0 ;
26
+ } else {
27
+ int leftDepth = depth (root -> left );
28
+ int rightDepth = depth (root -> right );
29
+ return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1 ;
30
+ }
31
+ }
32
+
33
+ void test () {
34
+ /* see images/example_binary_tree.png */
35
+ Node * root = createNode (1 );
36
+ Node * node2 = createNode (2 );
37
+ Node * node3 = createNode (3 );
38
+ Node * node4 = createNode (4 );
39
+ Node * node5 = createNode (5 );
40
+
41
+ root -> left = node2 ;
42
+ root -> right = node3 ;
43
+
44
+ node2 -> left = node4 ;
45
+ node2 -> right = node5 ;
46
+
47
+ node3 -> left = node3 -> right = NULL ;
48
+ node4 -> left = node4 -> right = NULL ;
49
+ node5 -> left = node5 -> right = NULL ;
50
+
51
+ assert (depth (root ) == 3 );
52
+ }
53
+
54
+ int main () {
55
+ test ();
56
+ return 0 ;
57
+ }
You can’t perform that action at this time.
0 commit comments