def preorder_children(children, root): result, pending = [], [root] while pending: node = pending.pop() result.append(node) pending.extend(reversed(children[node])) return result children = {"orchard":["north", "south"], "north":["oak"], "south":[], "oak":[]} print(preorder_children(children, "orchard"))