So, I’ve come up with a solution for one of the RECURSION VS. ITERATION - CODING THROWDOWN lessons that seems very different than the suggested one, although it works in the test cases.
Here’s my code. The
tree is a dictionary implementation of a binary tree.
def depth(tree): level = 1 for i in tree.values(): if isinstance(i, dict): return level + depth(i) return level
The point of the code is to find the depth of the given binary tree.
The suggested pseudo-code, on the other hand, seems a lot more complex than mine:
# function takes "tree_node" as input # BASE CASE # if tree_node is None # return 0 # RECURSIVE STEP # set left_depth to recursive call passing tree_node's left child # set right_depth to recursive call passing tree_node's right child # if left_depth is greater than right depth: # return left_depth + 1 # else # return right_depth + 1
Any idea of whether mine would still work in every case like the suggested code or whether it has limitations. As far as the test cases go, it works. It just seems to simple to be ‘good enough’ if you know what I mean.