How to count the number of correct children in a binary tree?
5 answers
In a recursive approach
You will call a function to traverse your tree, for the current node you need to: check if the current node has the correct child (then increment the counter) and then the function is called recursively for the right node. check if the current node has left a child, the function is called recursively for the left node.
This should work.
+1
a source to share
Simple tree traversal (i.e. order in order) and for each node do +1 if it has the correct child.
Example (didn't try to compile and test it):
int countRightChildren(Node root)
{
if (root == null) return 0;
int selfCount = (root.getRightChild() != null) ? 1 : 0;
return selfCount + countRightChildren(root.getLeftChild()) + countRightChildren(root.getRightChild());
}
+1
a source to share
You can do it recursively like:
- If the tree does not exist, there are no R children.
- If the tree exists, then # R children
=
# R children in the R subtree+
# R children in the L subtree
...
int countRChildren(Node *root) {
if(!root) // tree does not exist.
return 0;
// tree exists...now see if R node exits or not.
if(root->right) // right node exist
// return 1 + # of R children in L/R subtree.
return 1 + countRChildren(root->right) + countRChildren(root->left);
else // right nodes does not exist.
// total count of R children will come from left subtree.
return countRChildren(root->left);
}
0
a source to share
This includes how I am building the struct
struct Item
{
int info;
struct Item* right;
struct Item* left;
};
typedef struct Item* Node;
int countRightSons(Node tree)
{
if(!tree)
return 0;
if(tree->right != NULL)
return 1 + countRightSons(tree->right) + countRightSons(tree->left);
return countRightSons(tree->left);
}
0
a source to share