recursion - 从树上的递归到数组上的迭代(kd-tree 最近邻)

标签 recursion nearest-neighbor kdtree

我有一个递归函数(在树上),我需要让它在没有递归的情况下工作,并将树表示为隐式数据结构(数组)。

函数如下:

kdnode* kdSearchNN(kdnode* here, punto point, kdnode* best=NULL, int depth=0)
{   
if(here == NULL)
    return best;

if(best == NULL)
    best = here;

if(distance(here, point) < distance(best, point))
    best = here;

int axis = depth % 3;

kdnode* near_child = here->left;
kdnode* away_child = here->right;

if(point.xyz[axis] > here->xyz[axis])
{
    near_child = here->right;
    away_child = here->left;
}

best = kdSearchNN(near_child, point, best, depth + 1);

if(distance(here, point) < distance(best, point))
{
    best = kdSearchNN(away_child, point, best, depth + 1);
}

return best;
}

我使用这个属性将树表示为一个数组:

root: 0
left: index*2+1
right: index*2+2

enter image description here

这是我所做的:

punto* kdSearchNN_array(punto *tree_array, int here, punto point, punto* best=NULL, int depth=0, float dim=0)
{
if (here > dim) {
    return best;
}

if(best == NULL)
    best = &tree_array[here];

if(distance(&tree_array[here], point) < distance(best, point))
    best = &tree_array[here];

int axis = depth % 3;

int near_child = (here*2)+1;
int away_child = (here*2)+2;

if(point.xyz[axis] > tree_array[here].xyz[axis])
{
    near_child = (here*2)+2;
    away_child = (here*2)+1;
}

best = kdSearchNN_array(tree_array, near_child, point, best, depth + 1, dim);

if(distance(&tree_array[here], point) < distance(best, point))
{
    best = kdSearchNN_array(tree_array, away_child, point, best, depth + 1, dim);
}

return best;
}

现在最后一步是摆脱递归,但我找不到办法,有什么提示吗? 谢谢

最佳答案

你总是 self 递归,所以你可以把整个函数体包裹在一个循环中,在你想继续搜索的地方,简单地设置新的参数并继续循环?

关于recursion - 从树上的递归到数组上的迭代(kd-tree 最近邻),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5476499/

相关文章:

java - 使用递归方法在给定根 : what am I doing wrong here? 的子树中查找最小元素

c - 将数组传递给函数并通过递归添加它

python - 使用加权距离度量的 Scikit-learn 最近邻搜索

python - 为什么 Scipy 的 KDTree 这么慢?

algorithm - 处理边界框内移动点接触和包含的数据结构?

c - 在 C 中递归期间数组会发生什么?

java - java或python中范围的递归最大函数

java - 如何用 Java 构建 KDTree

python - 使用 NearestNeighbors 和 word2vec 检测句子相似度

java - 使用 MapReduce 构建 k-d 树?