[Solved] Traverse Non-Binary Tree [closed]


def traverse(tree_of_lists):
    for item in tree_of_lists:
        if isinstance(item, list):
            for x in traverse(item):
                yield x
        else:
            yield item

This is the “basic” solution — can run in Python 2.7 and gives you an iterable that you can simply loop on. (In recent Python 3.* versions you’d use yield from item instead of the inner for loop).

The isinstance test is unpleasant but depending on your exact problem it may be the only way to distinguish a “scalar item” from a “sub-tree”. There may be better ones but you don’t give us enough information to be able to tell. For example, if all “leaves” (scalars) are strings, you might prefer to check for that (still an isinstance check, alas!).

6

solved Traverse Non-Binary Tree [closed]