refactor to use depth-first instead of breadth-first