遍历树并计算特殊节点的总和

时间:2019-03-27 06:28:07

标签: c# recursion tree

我有以下课程:

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)

我想要做的是创建一个函数,该函数根据以下算法返回最大的年龄总和,其中Include设置为true

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

示例:首先计算:

  • 12 + 10 + 23 = 45(埃里克+约翰+比尔)
  • 12 + 100 = 112(埃里克+保罗)
  • 12(约翰,因为杰伊(Jay)将“包含”设置为false忽略比利(Billy))

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

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

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

1 个答案:

答案 0 :(得分: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);
相关问题