Search code examples
c#recursionsum

Aggregating totals using recursion - works one parent-child level only


I have a treeview control with a list of objects attached to each node. When a node is selected I want to know the total count of objects for the selected node and all its children.

The recursive function traverses the tree as expected but I am not aggregating the sums correctly. It only adds values from the current node and the children one level down.

I am sure the last line in my code is incorrect (return n.Maps.Count), but I don't know how to aggregate the values if the hierarchy is deeper than one level.

Appreciate any help. Regards Chris

private void CallingFunction()
{
    .... <some unrelated code> ...

    foreach (GeoSchemeTreeNode n in node.Nodes)
    {
        xx += AddTotal(n);
    }

    Console.WriteLine($"total={xx});
}

private int AddTotal(GeoSchemeTreeNode n)
{
    foreach (GeoSchemeTreeNode i in n.Nodes)
    {
        AddTotal(i);
    }

    return n.Maps.Count;
}

Solution

  • Your issue seems to be that you aren't actually storing and totalling the product of the recursions.

    The fixed method should look something like this:

    private int AddTotal(GeoSchemeTreeNode n)
    {
        int total = n.Maps.Count;
    
        foreach (GeoSchemeTreeNode i in n.Nodes)
        {
            total += AddTotal(i);
        }
    
        return total;
    }