简体   繁体   中英

Binary Tree - Count Distinct Nodes

If I was asked about number of nodes in binary tree, it would be so easy but I am asked to count number of distinct nodes in binary tree like below. There are two 12 values! 二叉树

Number of nodes in binary tree algoritm is this:

struct Node {
    string data;
    struct Node *left;
    struct Node *right;
};

int getNumberOfNodes(Node* node)
{
    if (node != NULL)
        return getNumberOfNodes(node->left) + 1 + getNumberOfNodes(node->right);
    else
        return 0;
}

But for unique values, it is too hard -_-

You can change your function adding a container to maintain the values you already encountered. The best container has been suggested in the comment std::set .

The new code would be:

int getNumberOfNodes(Node* node, std::set<string>& uniqueValues)
{
    if (node != NULL)
    {
       int count = 0;
       if ( uniqueValues.find( node->data ) == uniqueValues.end() )
       {
          count = 1;
          uniqueValues.insert ( node->data );
       }

       return getNumberOfNodes(node->left,uniqueValues) + count + getNumberOfNodes(node->right,uniqueValues);
    }
    else
        return 0;
}

Not so different from your code.
At the end the uniqueValues.size() will be equal to the returned int.
Clear the uniqueValues before calling the function.

int count_label(Node *root, int data)
{
    int count_of_data = 0;
    if(root == NULL)
    return 0;
    if(data == root->data)
    count_of_data += 1;
    if(data > root->data)
        count_of_data += count_label(root->right,data);
    else
        count_of_data += count_label(root->left,data);

    return count_of_data;
}
//--------------------------------------------------------
unsigned int unique_nodes(Node *root)
{
    int count_u = 0;
    if(root == NULL)
        return 0;
    if(count_label(root, root->data) == 1)
    {
        count_u += 1;
    }
    count_u += unique_nodes(root->left);
    count_u += unique_nodes(root->right);
    return count_u;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM