Reputation:
I'm trying to list all possible moves from the root to all of the leafs in a tree. I currently have it setup so I can get a list ['A', ['B', ['C'], ['K']], ['D', ['E', ['F'], ['G']], ['H', ['I'], ['J']]]]
Here is an image of what the list represents:
I'm just wondering how I can transform the above list into: "ABK", "ABC", "ADEF", "ADEG", "ADHI", "ADHJ"
I've tried recursion through the list but I can't quite figure it out. Btw the only reason I'm trying to use the list is because thats the only real way I could think of and it doesn't seem to much of a strech from the list into the different pathways?
Upvotes: 1
Views: 111
Reputation: 2411
Here's a suggestion!
def walktree(lst):
# Is it a leaf? Here's our base case.
if len(lst) == 1:
return lst
# If not, then it's a node; just make sure the list is formatted correctly.
assert(len(lst) == 3)
first = lst[0]
# Here's where the recursion happens.
left = walktree(lst[1])
right = walktree(lst[2])
# Finally, the combination step.
return [first + x for x in left + right]
Upvotes: 1