using System.Collections.Generic;
public class TreeRepresentation
public TreeRepresentation(int i, int v, string h)
id = i; value = v; hierarchy = h;
public class TreeStructure
public TreeStructure(int i, int v)
public List<TreeStructure> children = new List<TreeStructure>();
public static class Program
public static List<TreeRepresentation> treeRepresentation;
public static List<TreeStructure> LoadTree(List<TreeRepresentation> treeRepresentation)
List<TreeStructure> result = new List<TreeStructure>();
foreach (var t in treeRepresentation)
var n = new TreeStructure(t.id, t.value);
PositionNode(result, n, t.hierarchy);
private static void PositionNode(List<TreeStructure> forrest, TreeStructure n, string hierarchy)
var nodeIds = hierarchy.Split(".");
if (int.Parse(nodeIds[0]) == 0)
else if (!AddNode(forrest, int.Parse(nodeIds[0]), n))
private static bool AddNode(List<TreeStructure> nodes, int id, TreeStructure node)
if (AddNode(n.children, id, node))
public static void Main()
treeRepresentation = new List<TreeRepresentation> {
new TreeRepresentation(1, 2, "0"),
new TreeRepresentation(2, 3, "0"),
new TreeRepresentation(3, 4, "0"),
new TreeRepresentation(4, 3, "1.0"),
new TreeRepresentation(5, 4, "4.1.0"),
new TreeRepresentation(6, 4, "5.4.1.0"),
new TreeRepresentation(7, 4, "2.0"),
new TreeRepresentation(8, 9, "7.2.0"),
new TreeRepresentation(9, 5, "2.0")
var nodes = LoadTree(treeRepresentation);
Console.WriteLine($"The sum of all nodes is {SumValue(nodes)}");
PrintResultingTree(nodes, 0);
private static void PrintResultingTree(List<TreeStructure> nodes, int level)
if (nodes == null) return;
foreach(var node in nodes)
for (int i = 0; i < level; i++) Console.Write("\t");
Console.WriteLine($"id: {node.id}, value: {node.value}");
if (node.children.Count > 0)
PrintResultingTree(node.children, level + 1);
public static int SumValue(List<TreeStructure> nodes)
private static int SumNode(TreeStructure node)
if (node.children != null)
foreach (var t in node.children)
result += Program.SumNode(t);