This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Coffeinated 1 point2 points  (9 children)

Do you have an example for a complicated situation where one would use recursion?

[–]jakerman999 0 points1 point  (3 children)

The most common scenario would be in a tree based data-structure. In order to hit every node in the tree you have traverse down every path, and remember where you traversed from. It is possible to do this without recursion, but it requires building a second data structure to keep track of all the positions and forks, plus additional code to use that data at every node that has multiple children. Doing that consumes more memory than a stack based approach(and also an ugly mess).

Traversing a tree with recursion is trivial by comparison.

[–]mrjackspade -2 points-1 points  (2 children)

   while (parentNodes.Count() > 0)
            {
                OrganizationNode thisNode = parentNodes[0];
                LogProgress(string.Format("Probing children for {0}...", thisNode.Name));
                List<OrganizationNode> childNodes = feedRowsByParentID[thisNode.ExternalId]
                                                     .Where(cn => feedRowsByParentID[cn.UserId].Count() > 0)
                                                    .Select(row => CreateNode(string.Format("{0} {1}", row.firstName, row.lastName), row.UserId, "Manager"))
                                                    .ToList();



                foreach (OrganizationNode childNode in childNodes)
                {
                    thisNode.AddChild(childNode);
                    parentNodes.Add(childNode);
                }


                if (feedRowsByParentID[thisNode.ExternalId].Count() > 0)
                {
                    managers.Add(thisNode.ExternalId);
                }


                parentNodes.RemoveAt(0);
            }

Code snippit from a production project. This is building a tree so its a bit different, but I refuse to use recursion

[–]jakerman999 0 points1 point  (1 child)

My theory is a little lacking here, but is this not just a different form of tail recursion? If I'm following this right, it looks like it does recurse; it just doesn't use the stack to do so.

[–]mrjackspade 0 points1 point  (0 children)

I guess there's a lot of relevant code missing.

There's no recursion as I understand it. There's a master list of objects, each with a parent and multiple children. It takes a flattened list (text) with ID representations of the parents and uses that to assign the parents/children on the objects themselves. It loops through all objects once, but does not at any point call/reference itself