开发者

from recursion on tree to iterative on array (kd-tree Nearest Neighbor)

I've got a recursive function (on tree) and I need to make it work without recursion and representing the tree as an implicit data structure (array).

Here is the function:

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

I'm using this properties to represent the tree as an array:

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

from recursion on tree to iterative on array (kd-tree Nearest Neighbor)

This is what I've done:

punto* kdSearchNN_array(punto *tree_array, int here, punto point, punto* best=NULL, int depth=0, float dim=0)
{
if (h开发者_如何学Cere > 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;
}

Now the last step is to get rid of recursion, but I can't find a way, any hint? Thanks


You always self-recur, so you can just wrap the whole body of your function inside a loop, and in places where you want to continue searching, simply set the new parameters and continue looping?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜