-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_no_of_leaves_in_a_binary_tree.cpp
54 lines (45 loc) · 1.17 KB
/
count_no_of_leaves_in_a_binary_tree.cpp
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
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Fucntion to count two leaves */
int countLeaves(struct node* root)
{
// Your code here
if(!root) return 0;
if(root->left == NULL && root->right == NULL) return 1;
int l = countLeaves(root->left);
int r = countLeaves(root->right);
return l+r;
}
/* Driver program to test identicalTrees function*/
int main()
{
struct node *root1 = newNode(1);
root1->left = newNode(2);
root1->right = newNode(3);
root1->right->right = newNode(2);
root1->left->left = newNode(4);
root1->left->right = newNode(5);
int leaves= countLeaves(root1);
printf("number of Leaves are %d ",leaves);
getchar();
return 0;
}