Say we have a binary tree as follow: 
I’m looking for an algorithm to find all the equivalence of A. I’m given an array that contains elements in this tree. The rule is, if all the children of a node exist in an array, it is equivalent to having the node in the array.
For example, if we have B and C in the array, it is equivalent to having an A. So in the array above, F+G=C, and C+B = A, so [B,F,G] is also equivalent to A. Likewise [D E F G] is also equivalent to A.
I can recursively call something like checkSubstitute(node):
if node in array
return true
else:
for child in nodeChildren
if ((child not in array) && (child == terminalNode))
return false
else
return checkSubstitute(child)
Does this logic make sense? Also how can I store all the equivalent arrays using an algorithm like the one above?
Thanks in advance!!
The method you gave doesn’t work properly, since you always return a value during the first iteration of the for loop.
Suppose you have an array [D]. Then checkSubstitute(B) returns True, when it should return False.
Instead of using a for loop, it’s easier just to make two explicit calls on both of the children. This assumes every node has either zero or two children. If a node can have one child, some additional null checking is necessary.
getting all equivalent arrays just requires a bit of combinatorics.
Edit:
You can extend getPossibleEquivalents for trees with exactly 0 or N children, by nesting N for loops:
If you want to write a single function that can handle trees with any number of children, you need to take the Cartesian Product of each possible equivalent of each child. Some languages implement cartesian product for you already. For example, in python: