Skip to content

Commit 65ed1e3

Browse files
depth_of_binary_tree (#55)
1 parent 7070199 commit 65ed1e3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}

0 commit comments

Comments
 (0)