I'm stuck on a programming question involving a tree for a project. The problem itself is only a subproblem of the larger question (but I won't post that here as its not really relevant). Anyone the problem is:
I'm trying to go over each path in the tree and calculate the associated value.
The situation is for instance like in this tree:
a
b b
Now the result i should get is the multiplications as follows:
leave1 = a * b
leave2 = a * (1-b)
leave3 = (1-a) * b
leave4 = (1-a) * (1-b)
And so the leaves on one level lower in the tree would basically be the results (note that they do not exist in reality, its just conceptual).
Now, I want to do this recursively, but there are a few problems: The values for a and b are generated during the traversal, but the value for b for instance should only be generated 1 time. All values are either 0 or 1. If taking the left child of a node A, you use the value A in the multiplication. the right path you use the value 1-A.
Furthermore, the tree is always perfect, i.e. complete and balanced.
Now what I have (I program in python, but its more the algorithm in general im interested in with this question):
def f(n):
if n == 1:
return [1]
generate value #(a, b or whatever one it is)
g = f(n/2)
h = scalarmultiply(value,g)
return h.append(g - h)
Note that g and h are lists.
This code was giving by one of my professors as possible help, but I don't think this does what I want. At least, it wont give me as result a list h which has the result for each path. Especially, I don't think it differentiates between b
and 1-b
. Am I seeing this wrong and how should I do this?
I'm not very experienced at programming, so try and explain easy if you can :-)