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.
#returns true if Node n exists in NodeList seq, or if its equivalent exists in seq.
function exists(n, seq):
if n in seq:
return True
if not n.hasChildren:
return False
return exists(n.leftChild, seq) and exists(n.rightChild, seq)
getting all equivalent arrays just requires a bit of combinatorics.
#gets all possible equivalents for the given node. This includes itself.
#An equivalent is a list of nodes, so this method returns a list of lists of nodes.
function getPossibleEquivalents(node):
ret = new List()
baseCase = new List()
baseCase.append(node)
ret.append(baseCase)
if not node.hasChildren:
return ret
for each leftEquivalent in getPossibleEquivalents(node.leftChild):
for each rightEquivalent in getPossibleEquivalents(node.rightChild):
ret.append(leftEquivalent + rightEquivalent)
return ret
Edit:
You can extend getPossibleEquivalents for trees with exactly 0 or N children, by nesting N for loops:
for each child0Equivalent in getPossibleEquivalents(node.child[0]):
for each child1Equivalent in getPossibleEquivalents(node.child[1]):
for each child2Equivalent in getPossibleEquivalents(node.child[2]):
for each child3Equivalent in getPossibleEquivalents(node.child[3]):
for each child4Equivalent in getPossibleEquivalents(node.child[4]):
ret.append(child0Equivalent + child1Equivalent + child2Equivalent + child3Equivalent + child4Equivalent + child5Equivalent)
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:
from itertools import product
def getPossibleEquivalents(node):
ret = [node]
if len(node.children) == 0: return ret
for equivalentTuple in product(map(getPossibleEquivalents, node.children)):
possibleEquivalent = reduce(lambda x,y: x+y, equivalentTuple)
ret.append(possibleEquivalent)
return ret