Write a iterative function singleParent that returns the num
Write a iterative function, singleParent,
that returns the number of the nodes in a binary tree that have only one child. in c++
Solution
#include <iostream>
#include<stack>
using namespace std;
struct treenode
{
int data;
treenode *left,*right;
};
treenode* newNode(int data)
{
treenode *temp = new treenode;
temp->data = data;
temp->right = NULL;
temp->left = NULL;
return temp;
}
bool singleChild(treenode *temp)
{
if((temp->left!=NULL && temp->right==NULL) || (temp->left==NULL && temp->right!=NULL))
return true;
else
return false;
}
int numberOfNodesWithSingleChild(treenode *root)
{
/* set current to root of binary tree */
struct treenode *current = root;
stack<treenode*> s;
bool done = 0;
int count = 0;
while (!done)
{
if(current != NULL)
{
s.push(current);
current = current->left;
}
else
{
if (!s.empty())
{
current = s.top();
s.pop();
if(singleChild(current))
count++;
current = current->right;
}
else
done = 1;
}
} /* end of while */
return count;
}
int main()
{
treenode *root = NULL;
root = newNode(10);
root->left = newNode(11);
root->left->left = newNode(12);
root->left->right = newNode(13);
root->left->left->left = newNode(14);
int count = numberOfNodesWithSingleChild(root);
cout << \"Number of nodes with single child is : \" << count << endl;
return 0;
}

