-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountLeafs.C
143 lines (141 loc) · 2.88 KB
/
CountLeafs.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <stdio.h>
#include <stdlib.h>
static int count = 0;
struct tnode
{
int data;
struct tnode *left;
struct tnode *right;
};
struct qnode
{
struct tnode *dat;
struct qnode *next;
};
struct qnode *addq(struct qnode *rear, struct tnode *dat)
{
struct qnode *new_node = (struct qnode *)malloc(sizeof(struct qnode));
new_node->dat = dat;
if (rear == NULL)
{
new_node->next = NULL;
rear = new_node;
return rear;
}
else
{
struct qnode *b = rear;
while (b->next != NULL)
{
b = b->next;
}
b->next = new_node;
new_node->next = NULL;
return rear;
}
}
struct tnode *delq(struct qnode **front)
{
if (*front == NULL)
{
printf("\n");
}
else
{
struct qnode *s = *front;
struct tnode *j = s->dat;
*front = s->next;
s->next = NULL;
free(s);
s = NULL;
return j;
}
}
int isEmpty(struct qnode *front)
{
if (front == NULL)
{
return 0;
}
}
int countleaf(struct tnode *root)
{
if (root == NULL)
{
return 0;
}
struct tnode *y = root;
struct qnode *s = NULL;
s = addq(s, root);
while (isEmpty(s) != 0)
{
y = delq(&s);
if (y->left != NULL)
{
s = addq(s, y->left);
}
if (y->right != NULL)
{
s = addq(s, y->right);
}
if (y->left == NULL && y->right == NULL)
{
count = count + 1;
}
}
return count;
}
/*unsigned int getLeafCount(struct tnode *node)
{
if (node == NULL)
return 0;
if (node->left == NULL && node->right == NULL)
return 1;
else
return getLeafCount(node->left) +
getLeafCount(node->right);
}*/
struct tnode *new_node(int data)
{
struct tnode *nn = (struct tnode *)malloc(sizeof(struct tnode));
nn->left = NULL;
nn->right = NULL;
nn->data = data;
return nn;
}
struct tnode *insert(struct tnode *root, int data)
{
if (root == NULL)
{
root = new_node(data);
return root;
}
else if (data <= root->data)
{
root->left = insert(root->left, data);
}
else
{
root->right = insert(root->right, data);
}
return root;
}
int main()
{
struct tnode *root = NULL;
int t, opt;
do
{
printf("\nEnter option number: 1. Enter element\t0. Stop adding");
scanf("%d", &opt);
if (opt == 1)
{
printf("\nEnter the element: ");
scanf("%d", &t);
root = insert(root, t);
}
} while (opt != 0);
int jo = countleaf(root);
printf("Leaf count of the tree is: %d", jo);
return 0;
}