我有一个普通的二叉树,我试图应用迭代加深深度第一次搜索使用c:
struct node {
int data;
struct node * right;
struct node * left;
};
typedef struct node node;
我正在使用一个函数将节点插入到树中,现在我需要实现搜索功能,如下所示: function search(root,goal,maxLevel)
所以它使用深度优先搜索但搜索到特定的最大级别然后停止这是我的第一次尝试,它没有工作:
currentLevel = 0;
void search(node ** tree, int val, int depth)
{
if(currentLevel <= depth) {
currentLevel++;
if((*tree)->data == val)
{
printf("found , current level = %i , depth = %i", currentLevel,depth);
} else if((*tree)->left!= NULL && (*tree)->right!= NULL)
{
search(&(*tree)->left, val, depth);
search(&(*tree)->right, val, depth);
}
}
}
请帮忙,谢谢......
2 回答
你永远不会停止......
全局变量不适用于此 . 你想拥有类似的东西
然后
您可能还需要分别检查left和right for null,因为每个都可以独立为null .