First problem where I used recursion. Traversing trees is just so much easier with recursion.
I created the tree by creating a recursive algorithm to create nodes and return the head node. With that, the first part of the problem is solved by summing the metadata for each node and adding to it the sum of the metadata of it's children recursively. This is easily done using LINQ's aggregate function (similar to reduce in LISP):
public int MetadataSum()
{
return children.Aggregate(metadata.Sum(), (acc, cur) => acc + cur.MetadataSum());
}
As for the second part of the problem, calculating the value is just a more complicated sum, which can also be solved using an aggregation:
public int Value()
{
return children.Any() ? metadata.Aggregate(0, (acc, md) => acc + ChildValue(md)) : metadata.Sum();
}
private int ChildValue(int childIndex)
{
return childIndex > children.Count ? 0 : children[childIndex-1].Value();
}