I’m trying to experiment with recursion so as to grasp the concept. It is language agnostic, so the same concept applies to both C# and Java.
I’ve got a TreeView which has a number of nodes. I would like to iterate through every single node and count the ones which satisfy a certain condition. If at any time the condition is not satisfied, I would like the algorithm to finally return -1.
Each TreeViewItem will only be considered if it has a Tag named “Condition” (there are 3 types of TreeViewItems in all – I will only consider the “Condition” ones).
Once a TreeViewItem is found to be of the “Condition” type, I would like to check to see that it satisfies a certain condition. As I mentioned before, even if only one TreeViewItem does not satisfy the condition, I want the algorithm to return -1 in the end.
If the algorithm does not return -1, I want it to return the amount of valid conditions which it has found – i.e. an integer is to be incremented each time a condition is successfully passed, and the final count is returned at the end.
This is what I’ve tried so far:
private int CountConditions(TreeViewItem item)
{
int conditionCount = 0;
foreach (TreeViewItem child in item.Items)
{
int previousCount = CountConditions(child);
if (previousCount == -1)
{
return -1;
}
else
{
return conditionCount += previousCount;
}
}
if (item.Tag.Equals("Condition"))
{
if (/*Condition is not satisfied*/)
{
return -1;
}
else
{
return conditionCount++;
}
}
else
{
return conditionCount;
}
}
My current algorithm does infact return -1 if a condition is not satisfied, however if conditions are satisfied it just returns 0, rather than the amount of valid conditions.
It is not a trivial recursion, since you have to handle both the error condition, and the normal condition. If you didn’t have the error condition, and only needed to count the number of condition nodes, you could write:
But to handle the error, you have to have two checks for the error condition, one for the current node, and one for the child nodes, and return immediately, if you encounter the condition: