Reorganize depth-first traversal methods to avoid code duplication