You could use a tree structure, or just save everything locally and recurse. Depends if you're using a depth-first or breadth-first algorithm.