我有一个递归函数(在树上),我需要让它在没有递归的情况下工作,并将树表示为隐式数据结构(数组)。
这是功能:
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;
}
现在最后一步是摆脱递归,但我找不到方法,有什么提示吗?谢谢