【问题标题】:Find the sum of all count properties in child nodes查找子节点中所有计数属性的总和
【发布时间】:2020-08-06 08:31:45
【问题描述】:

我有以下 TreeJSON 类。

public class TreeJSON
{
    public string name;
    public int count;
    public int level;
    public int sum;
    public List<TreeJSON> children;
}

我正在尝试通过添加所有后代的 count 属性来设置父节点的 sum 属性 到 parent 的 count 属性。我尝试使用以下递归函数,但没有得到正确的总和值。

    public static void FindSum(TreeJSON data)
    {
        if (data.children == null)
            return;

        foreach (var item in data.children)
        {
            FindSum(item);
        }

        foreach (var item in data.children)
        {
            data.sum = data.sum + item.count;
        }

        data.sum = data.sum + data.count;
    } 

如果有人能指出正确的方向,我将不胜感激。

【问题讨论】:

  • 提示:您现在添加的所有内容都是零。您需要在某处添加 1 来计算节点本身,而不仅仅是子节点。

标签: c# linq


【解决方案1】:

您可以尝试实施广度优先搜索

 public static int FindSum(TreeJSON node) {
   if (null == node)
     return 0; // Or throw ArgumentNullException(nameof(node)); 

   int result = node.count; // or 0 if node itself should be excluded

   if (null == node.children)
     return result; 

   Queue<TreeJSON> agenda = new Queue<TreeJSON>(node.children);  

   while (agenda.Count > 0) {
     TreeJSON item = agenda.Dequeue();

     result += item.count; 

     if (item.children != null)
       foreach (var child in item.children)
         agenda.Enqueue(child);
   }

   return result;
 }

【讨论】:

    【解决方案2】:

    由于问题被标记为linq

    public static int FindSum(TreeJSON node) => node.count + node.children.Sum(n => FindSum(n));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2021-06-22
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多