Calculation of the number of all nodes and leaf nodes of a binary tree

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.

  1. Solution one
int n;
void count(BTNode* p)
{
    
    
    if(p)
    {
    
    
        ++n;
        count(p->left);
        count(p->right);
    }
}
  1. 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.

  1. A solution
    to a question on a solution in n++use if(p->left&&p->right) n++;.
  2. 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;
    }
}

Guess you like

Origin blog.csdn.net/Cxf2018/article/details/105552286