Ауууууууууууу, а сколько рекурсии!Просто хотел указать, что рекурсия абсолютно злая, и я лично избегаю ее везде, где могу (на самом деле, вы всегда можете избежать этого).
Просто чтобы найти альтернативное решение здесь, в этой теме.Если ваше дерево отсортировано, вы можете просто сделать:
int levelNode(struct Node* root, int a)
{
node *temp = root;
int level = 0;
while (temp != NULL)
{
if (temp->data == a)
break;
level ++;
if (a > temp->data)
temp = temp->right;
else if (a < temp->data)
temp = temp->left;
}
if (temp == NULL)
return 0;
if (temp->data == a)
return level;
return 0;
}
В случае, если ваше дерево не отсортировано, вы можете немного адаптировать мой код, чтобы сделать «правильную» полноценную BFS.
Как то так:
#include <stdio.h>
#include <queue>
#include <map>
int levelNode(struct Node* root, int a)
{
std::queue<Node*> stack;
std::map<Node*, int> xmap;
stack.push(root);
xmap[root] = 0;
while (!queue.empty())
{
Node* f = queue.front();
if(f == NULL) return;
queue.pop();
if(f->data == a) return xmap[f];
if(f->left){
queue.push(f->left);
xmap[f->left] = xmap[f]+1;
}
if(f->right){
queue.push(f->right);
xmap[f->right] = xmap[f]+1;
}
}
return 0;
}