Implemented transitive closure function