18/38
Part 4 of 7 · PathsLearn

When a tree arrives as nested objects that only point down, there's no parent to climb. Find the path with a walk down that keeps the current path in a list. Append on the way in, and pop on the way out when the target wasn't below:

def path_down(children, top, target):
    path = []

    def visit(region):
        path.append(region)
        if region == target:
            return True
        for child in children[region]:
            if visit(child):
                return True
        # not under here: take it back off
        path.pop()
        return False

    visit(top)
    return path


print(path_down(children, "Europe", "Granada"))
['Europe', 'Spain', 'Andalusia', 'Granada']

The list grows on the way down and shrinks on the way back up:

Visitpath after it
EuropeEurope
PortugalEurope, Portugal
Portugal's subtreeits 7 regions go on, then come back off
back out of PortugalEurope
SpainEurope, Spain
AndalusiaEurope, Spain, Andalusia
SevilleEurope, Spain, Andalusia, Seville: not the target, so popped
GranadaEurope, Spain, Andalusia, Granada: the target, stop

This walk may visit the whole tree, O(n)O(n), against O(h)O(h) for the walk up. So build parent once if you'll ask more than one question. That path.pop() is your first undo step. Backtracking, later in this lesson, is built on it.