-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program to find count of nodes having 1 child
72 lines (61 loc) · 1.16 KB
/
Program to find count of nodes having 1 child
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
// C++ implementation to print
// the nodes having a single child
#include <bits/stdc++.h>
using namespace std;
// Class of the Binary Tree node
struct Node
{
int data;
Node *left, *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
vector<int> lst;
// Function to find the nodes
// having single child
void printNodesOneChild(Node* root)
{
// Base case
if (root == NULL)
return;
// Condition to check if the
// node is having only one child
if (root->left != NULL &&
root->right == NULL ||
root->left == NULL &&
root->right != NULL)
{
lst.push_back(root->data);
}
// Traversing the left child
printNodesOneChild(root -> left);
// Traversing the right child
printNodesOneChild(root -> right);
}
//Driver code
int main()
{
// Constructing the binary tree
Node *root = new Node(2);
root -> left = new Node(3);
root -> right = new Node(5);
root -> left -> left = new Node(7);
root -> right -> left = new Node(8);
root -> right -> right = new Node(6);
// Function calling
printNodesOneChild(root);
// Condition to check if there is
// no such node having single child
if (lst.size() == 0)
printf("-1");
else
{
for(int value : lst)
{
cout << (value) << endl;
}
}
}