javadata-structuresknnnearest-neighborkdtree

find m nearest neighbors in KD tree use java


I want to implement KD tree in java for a data structure project but I have problem with special method that this project wants. In below you can see the format of method that I want.

float[][] findMNearest(float[] point, int m) {}

I implement find nearest neighbor method but for m nearest neighbor I have problem and I can't understand algorithm for solution. In this picture you can see my implementation for nearest neighbor.

java
private void nearest(KDNode root, KDNode target, int index) {
        if (root == null)
            return;
        visited++;
        float d = root.distance(target);
        if (best == null || d < bestDistance) {
            bestDistance = d;
            best = root;
        }
        if (bestDistance == 0)
            return;
        float dx = root.getCoordinates()[index] - target.getCoordinates()[index];
        index = (index + 1) % k;
        nearest(dx > 0 ? root.getLeft() : root.getRight(), target, index);
        if (dx * dx >= bestDistance)
            return;
        nearest(dx > 0 ? root.getRight() : root.getLeft(), target, index);
    }

I don't want to use ready library, too.


Solution

  • At the end my friend help me!
    Full source of project for answer this question and other questions about kdtree and its methods at https://github.com/Iman9mo/KDTree