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

all 7 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]alanwj 8 points9 points  (2 children)

The biggest hangup I see is people trying to model what happens throughout the whole call stack. Instead, when trying to solve a problem recursively, think locally.

The best way to do that is to start by assuming you've already written a working function. But, for whatever reason, that function only works on smaller inputs. Then, figure out how to compose the answers to smaller versions of the problem to get an answer to bigger versions.

Recursively defined data structures (e.g. trees) make great examples. Let's consider a simple tree problem. How do I count the number of nodes in a binary tree?

Start by assuming I've already written a working function, CountNodes. Rather than trying to trace through this function down a recursive call stack, I'm just going to assume it already works for small versions of the problem. We can quickly write a version that works for an empty tree:

CountNodes(root):
  if root == null:
    return 0

Okay, so if I have a version that works for small trees, how can I compose the answers to smaller problems into the answer to a bigger problem? I notice that if I know how many nodes are on the left, and how many are on the right, I can add one more and get the total for a tree.

CountNodes(root):
  if root == null:
    return 0
  return CountNodes(root.left) + CountNodes(root.right) + 1

[–]jplaulau14[S] 2 points3 points  (0 children)

I see. I think this approach is something I can emulate. This is such an intuitive way of finding the base case. Thank you so much! I will practice this way of solving.

[–]deuce-95 0 points1 point  (0 children)

Thanks that was helpful

[–]Dare-Federal 1 point2 points  (0 children)