Java: replaced naive save order algorithm with proper depth-first search