1. Assuming that the binary tree adopts a binary chain storage structure, design an algorithm to calculate the number of all nodes in a given binary tree.
- Solution one
int n;
void count(BTNode* p)
{
if(p)
{
++n;
count(p->left);
count(p->right);
}
}
- Solution two
int count(BTNode* p)
{
int n1,n2;
if(!p)
return 0;
else
{
n1=count(p->left);
n2=count(p->right);
return n1+n2+1;
}
}
2. Assuming that the binary tree adopts a binary chain storage structure, design an algorithm to calculate the number of leaf nodes of a given binary tree.
- A solution
to a question on a solution inn++
useif(p->left&&p->right) n++;
. - Solution two
int count(BTNode* P)
{
int n1,n2;
if(!p)
return 0;
else if(!p->left&&!p->right)
return 1;
else
{
n1=count(p->left);
n2=count(p->eight);
return n1+n2;
}
}