Question

C++ programming Make a function or algorithm that can print/return #nodes with exactly two children in...

C++ programming

Make a function or algorithm that can print/return #nodes with exactly two children in a BST

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the C++ function/algorithm for return number of nodes with exactly two children in a BST:

int countTwoChildNodes(struct Node* root)
{
// Base cases
if (root == NULL) return 0;

//if leaf node, return 0
if ((root->left == NULL) && (root->left ==null)) return 0;
  
//if node with only one children
   if ( (root->left == NULL) && (root->left ==null)){
   return (countTwoChildNodes(root->left) + countTwoChildNodes(root->right));
   }
  
   //if a node has both left and right child
if ((root->left) && (root->right)){
   return 1+(countTwoChildNodes(root->left) + countTwoChildNodes(root->right));
   }
}


Screenshot:

int countTwoChildNodes (struct Node* root) { // Base cases if (root NULL) return; == //if Leaf node, return if (root->left ==

Explanation:

If there are no nodes in tree or if the current node is leaf (a node which don't have both left and right children) will return 0 as count.

But if a node has only 1 children, either left or right, don't count the node but has to continue search for node with 2 children from left or right children.

If a node has both left and right child, return count as 1 and continue search for node with 2 children for left and right children.

Add a comment
Know the answer?
Add Answer to:
C++ programming Make a function or algorithm that can print/return #nodes with exactly two children in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT