I'm trying to explore the binary tree. However, I have to implement recursive functions nonrecursively.
I've searched several ways to convert recursion to nonrecursive. But it doesn't seem to apply to my code.
I wonder if I can convert my code to non-recursive and how I can convert it.
This is my code(recursive function)
const NODE* getNN(const float pos[DIM], const NODE* cur, int depth) {
if (!cur) return nullptr;
bool flag = pos[depth % DIM] < cur->pos[depth % DIM];
NODE* next{ flag ? cur->left : cur->right };
NODE* other{ flag ? cur->right : cur->left };
const NODE* temp = getNN(pos, next, depth + 1);
const NODE* best{ closest(pos, temp, cur) };
float r = this->distance(pos, best->pos);
float dr = pos[depth % DIM] - cur->pos[depth % DIM];
if (r >= dr * dr) {
temp = getNN(pos, other, depth + 1);
best = closest(pos, temp, best);
}
return best;
}
Here is what I expected
const NODE* getNN_NonRecur(const float pos[DIM])