【问题标题】:Iterate over tree and calculate sum of special nodes遍历树并计算特殊节点的总和
【发布时间】:2019-08-17 15:48:15
【问题描述】:

我有以下课程:

public class Person
{
    public Person(string name, bool include, int age)
    {
        this.Name = name;
        this.Include = include;
        this.Age = age;
    }

    public string Name { get; set; }

    public bool Include { get; set; }

    public int Age { get; set; }

    public List<Person> Childs { get; set; }
}

我以这种方式创建对象:

var Persons = new List<Person>();
Persons.Add(new Person("Eric", true, 12));
Persons[0].Childs = new List<Person>();
Persons[0].Childs.Add(new Person("Tom", false, 13));
Persons[0].Childs.Add(new Person("John", true, 10));
Persons[0].Childs[0].Childs = new List<Person>();
Persons[0].Childs[0].Childs.Add(new Person("Bill", true, 23));
Persons[0].Childs.Add(new Person("Paul", true, 100));
Persons.Add(new Person("John", true, 12);
Persons[1].Childs = new List<Person>();
Persons[1].Childs.Add(new Person("Jay", true, 15));
Persons[1].Childs[0].Childs = new List<Person>();
Persons[1].Childs[0].Childs.Add(new Person("Billy", true, 23));

这会产生以下树:

-Eric (true, 12)
    -Tom (false, 13)
    -John (true, 10)
        -Bill (true, 23)
    -Paul (true, 100)
-John (true, 12)
    -Jay (false, 15)
        -Billy (true, 23)

我想做的是创建一个函数,该函数根据以下算法返回 Includeis 设置为 true 的最高年龄总和:

  • 必须选择包含设置为 true 的所有节点。
  • 从这些节点中,检索所有子节点和 Include 也设置为 true 的子节点,并计算每个可能联盟的年龄总和。返回最大的一个。
  • 当子节点的 Include 设置为 false 时,忽略子节点的所有子节点,即使它们已 Include 设置为 true。因此,计算从上到下的所有直接方式,其中 Include 设置为 true 并返回最大的方式。

示例:先计算:

  • 12 + 10 + 23 = 45(埃里克 + 约翰 + 比尔)
  • 12 + 100 = 112(埃里克 + 保罗)
  • 12(John,因为 Jay 已将 Include 设置为 false 忽略 Billy)

然后返回总和的最大值:112

编辑: 到目前为止我所尝试的

public int GetMax(Person p){
    foreach(var pi in p){
        if(pi.Include) {
            // how do I save sums?
         }
    }
}

【问题讨论】:

  • 你应该发布到目前为止你已经尝试过的内容。
  • 虽然你发了代码,但对后半部分提到的问题如何解决没有任何帮助。您实际上是在发布一组要求,这使您的问题过于宽泛。可悲的是,SO 不是代码编写服务。 How to Ask

标签: c# recursion tree


【解决方案1】:

你可以用递归来做到这一点,但是你也可以在课堂上把它扔掉。

internal class Person
{

   ...

   public int MaxStuff => Include ? Age + (Childs?.Max(x => x.MaxStuff) ?? 0) : 0;
}

用法

var total = persons.Max(x => x.MaxStuff);

或递归

public static int MaxStuff(Person p)
    => p.Include ? p.Age + (p.Childs?.Max( MaxStuff) ?? 0) : 0;

用法

var total = persons.Max(MaxStuff);

【讨论】:

  • 我必须用递归来做,但我不知道如何保存以前的总和值。
  • @bob 这是递归的 :) 只是不是一个独立的方法
  • 我的意思是在类外的函数中:)
  • 我必须承认我真的从这个练习中学到了一些东西,为我向你的老师说声谢谢
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 2020-08-15
  • 1970-01-01
  • 2020-11-20
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多