I'm brushing up on recursion problems and have no issues when the problem statement asks to print values (eg. BST traversal where you print the node values), and similarly few issues when the problem asks to return a list of values (return a path between 2 nodes in a tree) but am having problems when there are multiple answers, involving multiple lists (or a single 2D list) to be returned. For example the problem asks me to return how many ways a child can reach the top of the stairs, assuming it can jump either 1, 2, or 3 steps at a time. This is no problem and is solved below
def step_helper(steps):
if(steps == 0):
return 1
elif(steps < 0):
return 0
else:
return step_helper(steps-1) +
step_helper(steps-2) +
step_helper(steps-3)
def find_num_ways(steps):
count = step_helper(steps)
print(count)
find_num_ways(10)
Similarly if I need to return a path from two nodes in a BST, returning 1 list is no problem
def another_path_helper(self, n1, n2):
if(n1 == None):
return [None]
elif(n1 == n2):
return [n1.data]
elif(n1.data > n2.data):
return [n1.data] + self.another_path_helper(n1.left, n2)
elif(n1.data < n2.data):
return [n1.data] + self.another_path_helper(n1.right, n2)
else:
return None
def another_path(self, n1, n2):
path = self.another_path_helper(n1, n2)
if(None in path):
return None
else:
return path
However, I'm clueless on how I would return a list of lists. In the child-steps example, instead of returning the number of ways a child can climb the stairs, how could I return a list of paths, which would be a 2d list, where each entry would be a list of steps taken to get from bottom to top? Ideally I would not need to pass a list as argument to my recursive function since I've been told passing mutable objects to recursive functions is a bad practice and no different from using a static counter.