altered recursive deletion algorithm to avoid cycles