【发布时间】:2013-04-20 22:49:25
【问题描述】:
我有一个正常的二叉树,我试图在使用 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);
}
}
}
请帮忙,谢谢...
【问题讨论】:
-
请描述什么不起作用。
-
为什么不每次深入时减少
depth?然后检查它是否大于零。 -
你可能不想要一个全局变量
currentLevel()。您可能不应该同时搜索左子树和右子树 - 如果值小于当前节点中的值,您应该搜索左子树,如果值大于当前节点中的值,则应该搜索右子树当前节点的值。您可能需要将指针返回到找到值的节点;您可能需要一些方法来区分“未找到”、“太深”和“找到”。 -
由于您没有修改树,因此没有明显的理由使用
node **tree作为参数;使用node *tree(或者,更好的是const node *tree)就足够了。
标签: c depth-first-search iterative-deepening