C++ 我的KD树怎么了?(K=2)

C++ 我的KD树怎么了?(K=2),c++,algorithm,data-structures,C++,Algorithm,Data Structures,更具体地说,我的近邻搜索有问题。我已经确认树是正确构建的,并且所有助手函数都按照预期工作 请注意,这与标准KD树略有不同,因为我正在寻找最接近的3个点 struct Node { unsigned int axis; Point* obj; struct Node* left; struct Node* right; }; void _findClosest(struct Node* current, Point* to, Point** first, Point** second, Po

更具体地说,我的近邻搜索有问题。我已经确认树是正确构建的,并且所有助手函数都按照预期工作

请注意,这与标准KD树略有不同,因为我正在寻找最接近的3个点

struct Node
{
unsigned int axis;
Point* obj;

struct Node* left;
struct Node* right;
};


void _findClosest(struct Node* current, Point* to, Point** first, Point** second, Point** third, unsigned int depth)
{
if(current == NULL) return;

if(current->left == NULL && current->right == NULL)
{
            //_setOrder updates first, second, and third so that they point to
            //objects that are closest to "to", given an object and the current
            //current first, second, and third.
    _setOrder(to, current->obj, first, second, third);
    return;
}

unsigned int axis = depth % 2;
struct Node* other = NULL;

if(to->getValue(axis) < current->obj->getValue(axis))
{
    other = current->right;
    _findClosest(current->left, to, first, second, third, depth+1);
}
else
{
    other = current->left;
    _findClosest(current->right, to, first, second, third, depth+1);
}

_setOrder(to, current->obj, first, second, third);

if(other == NULL) return;

double searchToBest = _largestDistance(to, *first, *second, *third);
double searchToSplit = _distance(to, current->obj, current->axis);

    //This branch is ALWAYS taken, so this devolves into an O(n) search
if(searchToBest >= searchToSplit)
{
    _findClosest(other, to, first, second, third, depth+1);
}
}
我想我只是在某种程度上误解了数据结构/算法

次要细节: -如果对空对象调用距离函数,它们将返回std::numberic_limits::max -它在KD树的根上调用,深度为0,*first=*second=*third=NULL -轴=0对应X,轴=1对应Y

问题是每个节点都会被访问,而不是看到利用树属性所带来的预期减少。无论缺陷是什么,它都会使这成为一种搜索。

这一行是错误的:

双搜索分割=_距离到,当前->对象,当前->轴

您需要的是轴,而不是当前->轴。

此行错误:

双搜索分割=_距离到,当前->对象,当前->轴


你想要的是axis,而不是current->axis。

你能举个例子说明它做错了什么吗?在问题中澄清:基本上它可以工作,但它总是访问每个节点。你能举个例子说明它做错了什么吗?在问题中澄清:基本上它可以工作,但它总是访问每个节点。