-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.c
executable file
·114 lines (93 loc) · 1.95 KB
/
binary_tree.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
typedef struct {
int data;
struct node *left;
struct node *right;
} node;
void tree_insert(node **tree, node *item)
{
node *curr = *tree;
if (*tree == NULL)
{
*tree = item;
return;
}
if (item->data > curr->data)
{
tree_insert((node **)&(curr->right), (node *)item);
}
else
{
tree_insert((node **)&(curr->left), (node *)item);
}
}
void tree_parse(node *leaf)
{
if (leaf == NULL)
{
return;
}
tree_parse((node *)leaf->left);
printf("Node is %d\n", leaf->data);
tree_parse((node *)leaf->right);
}
int tree_count(node *leaf)
{
int count = 0;
if (leaf == NULL)
{
return 0;
}
count = 1 + tree_count((node *)leaf->left) + tree_count((node *)leaf->right);
return(count);
}
int max_depth(node *leaf)
{
int ldepth; int rdepth;
if (leaf == NULL)
{
return 0;
}
ldepth = max_depth((node *)leaf->left);
rdepth = max_depth((node *)leaf->right);
if (ldepth > rdepth)
return ldepth + 1;
else
return rdepth + 1;
}
int main()
{
int i, count =0;
node *head;
node *item;
head = NULL;
head = (node *)malloc(sizeof(node));
head->data = 1;
head->left = NULL;
head->right = NULL;
#if 1
for (i = 2; i < 9; i = i+2)
{
printf("adding item %d\n", i);
item = (node *)malloc(sizeof(node));
item->data = i;
item->left = NULL;
item->right = NULL;
tree_insert(&head, item);
}
for (i = 9; i > 2; i = i-2)
{
printf("adding item %d\n", i);
item = (node *)malloc(sizeof(node));
item->data = i;
item->left = NULL;
item->right = NULL;
tree_insert(&head, item);
}
#endif
count = tree_count(head);
printf("Num of nodes in tree is %d\n", count);
printf("max depth = %d\n", max_depth(head));
tree_parse(head);
return 1;
}