KNN and kdtree refactoring