Total Non-Leaf Nodes in Tree
int countNonLeafNodes(Node* root)
{
if(root==0)
return 0;
else if(root->right==0 && root->left==0)
return 0;
else
return 1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right);
}
{
if(root==0)
return 0;
else if(root->right==0 && root->left==0)
return 0;
else
return 1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right);
}
The total number or non leaf nodes will be equal to:
left-subtree + root(1) + right subtree
if left subtree have no child, i.e. left subtree->left==0 and left-subtree->right==0, then return 0.
if right subtree have no child, i.e. right subtree->left==0 and right-subtree->right==0, then return 0.
Comments
Post a Comment