【问题标题】:from recursion on tree to iterative on array (kd-tree Nearest Neighbor)从树上的递归到数组上的迭代(kd-tree Nearest Neighbor)
【发布时间】:2011-07-25 11:49:13
【问题描述】:

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

函数如下:

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

这就是我所做的:

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;
}

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

【问题讨论】:

    标签: recursion nearest-neighbor kdtree


    【解决方案1】:

    你总是自我递归,所以你可以将整个函数体包裹在一个循环中,在你想继续搜索的地方,只需设置新参数并继续循环?

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 2014-05-27
      • 2015-02-05
      • 2018-08-26
      • 2018-04-14
      • 2013-12-31
      相关资源
      最近更新 更多