Reputation: 137
So like I have this problem and I have no idea how to do it at all. The problem goes like this:
Define a recursive function called subt_tree() that takes a Binary-Number-Tree and recursively subtracts the value of each right branch from the left branch. So for example, if
tree1 = (25,((10,4),(12,11)))
then subt_tree(tree1)
would return
( 25 - ( (10-4) - (12-11) ) ) = ( 25 - ( 6 - 1 ) ) = ( 25 - 5 ) = 20.
So essentially I have to make each tuple
into a subtraction problem and then solve.
I've tried this:
def subt_tree(bnt):
"""Takes a bnt and recursively subtracts the value of each right branch from the left branch.
bnt -> number"""
if not isinstance(bnt,tuple):
return 1
else:
return subt_tree(bnt[0]) - subt_tree(bnt[1])
but there must be something wrong in my else statement because no matter what I input it will only return 0 or 1.
Upvotes: 0
Views: 286
Reputation: 21619
Instead of returning 1 why don't you return the value itself? That is after all the base case for your recursion.
i.e.
def subt_tree(bnt):
if not isinstance(bnt,tuple):
return bnt
else:
return subt_tree(bnt[0]) - subt_tree(bnt[1])
If you return 1 you'll only ever get a set of values consisting of 1 being subtracted from each other.
Upvotes: 2