Use recursion to get the value of parents and the value of children and all children's children enjoy

advertisements

Need help with the following question. I was tested on this and failed and really want to know the answer so that I can study it....

Assume an list (C#) of objects in pyramid structure with the following properties:

  • id
  • name
  • value
  • parentid

Example (C#):

var b = new block();
b.id = 100;
b.name = "block 100"
b.value = 102.50;
b.parentid = 99;

Write a recursive function that accepts an ID as the only parameter and will loop through an array or list of an undetermined size and number of levels. The recursive function will calculate


  block block1 = new block(1, null, "block 1", 11.34M);
    block block11 = new block(11, 1, "block 11", 234.34M);
      block block111 = new block(111, 11, "block 111", 111);
    block block12 = new block(12, 1, "block 12", 564);
    block block13 = new block (13, 1, "block 13", 342.23M);
      block block131 = new block(131, 13, "block 131", 945);
      block block132 = new block(132, 13, "block 132", 10M);
      block block133 = new block(133, 13, "block 133", 88M);
        block block1331 = new block(1331, 133, "block 1331", 45);

  block block2 = new block(2, null, "block 2", 234);
  block block3 = new block(3, null, "block 3", 1249.34M);

  blocks = new List<block>();
  blocks.Add(block1);
  blocks.Add(block11);
  blocks.Add(block111);
  blocks.Add(block12);
  blocks.Add(block13);
  blocks.Add(block131);
  blocks.Add(block132);
  blocks.Add(block133);
  blocks.Add(block1331);
  blocks.Add(block2);
  blocks.Add(block3);

  decimal sum = SumAll(1);
  Console.WriteLine(sum);
  Console.ReadKey();
}


I need a function that gives me a total "value" from the "value" property for the parent and all of its children and its children's children. Can anyone help?


public class block
{
    public block() { }

    public block(int id, int? parentid, string name, decimal value)
    {
        this.id = id;
        this.parentid = parentid;
        this.name = name;
        this.value = value;
    }

    public int id { get; set; }
    public int? parentid { get; set; }
    public string name { get; set; }
    public decimal value { get; set; }
}


To get you moving (and hopefully editing your question with what you've tried so far), you want something like this:

// defined at class level/scope outside method
private List<block> blocks;

...

private int SumAll(int id) {
      var initialBlock = blocks.FirstOrDefault(b => b.id == id);
      int value = initialBlock.Value;

      var childBlocks = blocks.Where(b => b.parentId = id).ToList();
      foreach (var childBlock in childBlocks) {
            // recursive call for children
            value += SumAll(childBlock.id);
      }

      return value;
}