【问题标题】:Iterative deepening depth-first search in binary tree二叉树中的迭代加深深度优先搜索
【发布时间】: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


【解决方案1】:

你永远不会停止...

node *search(node ** tree, int val, int depth)
{
    if (depth <= 0)
    {
        return NULL; // not found
    }

    if((*tree)->data == val)
    {
        return *tree;
    }

    if((*tree)->left)
    {
        node * left = search(&(*tree)->left, val, depth - 1);
        if (left) return left; // found
    }
    if((*tree)->right)
    {
        node * right = search(&(*tree)->left, val, depth - 1);
        return right; // whatever is result of right
    }
    return NULL; // not found
}

【讨论】:

  • 此实现将深度递减两次(左递归调用 1,右递归调用 1),因此不会达到所需的深度。
【解决方案2】:

全局变量对此不起作用。你想拥有类似的东西

void search(node ** tree, int val, int remainingDepth) {
    if (remainingDepth == 0) return;

然后

        search(&(*tree)->left, val, remainingDepth - 1);
        search(&(*tree)->right, val, remainingDepth - 1);

您可能还想分别检查左右是否为空,因为每个都可以独立为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多