# 总结树上的值[英] summarize values on a tree

### 问题描述

，但只有叶子(最后一个节点)具有整数值和父母的价值.

## 推荐答案

```public void SetNodeValues(Node node)
{
if (node.Name == String.Empty)
{
//If it has no name it is a leaf, which needs no value
return;
}
else
{
//Make sure all child-nodes have values
foreach (var childNode in node.ChildNodes)
{
SetNodeValues(childNode);
}

//Sum them up and set that as the current node's value
node.Value = node.ChildNodes.Sum(x => x.Value);
}
}
```

## 其他推荐答案

```class Node
{
public Node()
{
Children = new List<Node>();
}

public IEnumerable<Node> GetSubTree()
{
return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });
}

public List<Node> Children { get; set; }
public string Value { get; set; }
}

class Tree
{
public Tree()
{
Root = new Node();
}

public IEnumerable<Node> GetAllNodes()
{
return Root.Children.SelectMany(root => root.GetSubTree());
}

Node Root { get; set; }

//This is the Property you want:
public int GetValuesSum
{
get
{
return GetAllNodes().Where(node => !string.IsNullOrEmpty(node.Value)).Sum(node => Convert.ToInt32(node.Value));
}
}
}
```

### 问题描述

I used a Tree control to view some hierarchical items base on a nested (parent child) table .

Every node has a NameValue format that accept either a name and value .

But only Leaves (last nodes) have integer values and values of parents are left blank (just the Names they have) .

I want to summarize values so that every parent hold the sum of it's sub nodes and leaves values .

I think recursion or maybe LINQ is needed to accomplish this task but i don't know how ?

maybe some pseudo code will be helpful for me .

Thanks in advance for the help!

## 推荐答案

This is untested but i think it might work to set all the values of all nodes:

```public void SetNodeValues(Node node)
{
if (node.Name == String.Empty)
{
//If it has no name it is a leaf, which needs no value
return;
}
else
{
//Make sure all child-nodes have values
foreach (var childNode in node.ChildNodes)
{
SetNodeValues(childNode);
}

//Sum them up and set that as the current node's value
node.Value = node.ChildNodes.Sum(x => x.Value);
}
}
```

## 其他推荐答案

This will do it for you :

```class Node
{
public Node()
{
Children = new List<Node>();
}

public IEnumerable<Node> GetSubTree()
{
return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });
}

public List<Node> Children { get; set; }
public string Value { get; set; }
}

class Tree
{
public Tree()
{
Root = new Node();
}

public IEnumerable<Node> GetAllNodes()
{
return Root.Children.SelectMany(root => root.GetSubTree());
}

Node Root { get; set; }

//This is the Property you want:
public int GetValuesSum
{
get
{
return GetAllNodes().Where(node => !string.IsNullOrEmpty(node.Value)).Sum(node => Convert.ToInt32(node.Value));
}
}
}
```