I have a Task class which can have sub tasks of the same type
public class Task
{
public DateTime Start { get; set;}
public DateTime Finish { get; set;}
Svick's solution is fine, but I thought I'd add a bit more general advice. It seems like you are new to writing recursive methods and were struggling a bit there. The easiest way to write a recursive method is to strictly follow a pattern:
Result M(Problem prob)
{
if ()
return ;
// The problem cannot be solved easily.
Problem smaller1 =
Result result1 = M(smaller1);
Problem smaller2 =
Result result2 = M(smaller2);
...
Result finalResult =
return finalResult;
}
So suppose you want to solve the problem "what is the maximum depth of my binary tree?"
int Depth(Tree tree)
{
// Start with the trivial case. Is the tree empty?
if (tree.IsEmpty) return 0;
// The tree is not empty.
// Reduce the problem to two smaller problems and solve them:
int depthLeft = Depth(tree.Left);
int depthRight = Depth(tree.Right);
// Now combine the two solutions to solve the larger problem.
return Math.Max(depthLeft, depthRight) + 1;
}
You need three things to make recursion work:
If you cannot guarantee those three things then do not use a recursive solution.