简体   繁体   English

C语言实现的多路树搜索算法。

[英]Multiway Tree search algorithm in C implementation

typedef struct dt {
    .....;
} Data;

typedef struct nd {
    int id;
    Data *data;
    struct tm *_parent;
    struct tm *_child[7];
} Node; 


Node* findNode(int id, Node *tree) {
    Node *p = tree;
    if (id == p->_id)
        return p;
    for (int i = 0; i < 7; i++) {
        if (id == p->_child[i]->_id) {
            p = p->_child[i];
            break;
        } else if(p->_child[i] != NULL) {
            findNode(id, p->_child[i]);
        }
    }

    return p;
}

I have a multi-way tree for which every node consists of 0-7 children. 我有一棵多路树,每个树都包含0-7个孩子。 Children may be added and removed in no particular order. 子级可以不按特定顺序添加和删除。 I am trying to build a search algorithm that given an id will search the tree and return a pointer to the particular node. 我正在尝试建立一个搜索算法,给定一个id将搜索树并返回指向特定节点的指针。 I have tried to do it recursively as above, without much luck. 我已经尝试了如上所述的递归操作,但运气不佳。 Is it actually possible to build this algorithm recursively or do I also need to use a stack? 实际上是否可以递归地构建此算法,还是我还需要使用堆栈?

Is it actually possible to build this algorithm recursively? 实际上有可能递归地构建此算法吗?

Yes, it's possible to do this using recursion. 是的,可以使用递归来做到这一点。

You are on the right track. 您走在正确的轨道上。 The code just needs a couple of fixes: 该代码仅需要几个修复程序:

  1. The first part of if (id == p->_child[i]->_id)... is completely redundant as it duplicates what the recursive invocation will do anyway (and fails to check wether the child is NULL ). if (id == p->_child[i]->_id)...的第一部分是完全多余的,因为它重复了递归调用将要执行的操作(并且无法检查子元素是否为NULL )。
  2. When the function calls itself recursively, the return value is ignored. 当函数递归调用自身时,返回值将被忽略。 You need to figure out what to do with that return value. 您需要弄清楚如何处理该返回值。

There are some problems with your end conditions. 您的最终条件存在一些问题。 If the loop doesn't find the id, it must be detectable through the return value. 如果循环找不到ID,则必须可以通过返回值检测到它。 Making it NULL in that case would be sensible. 在这种情况下将其设置为NULL将是明智的。 This can be done by making two changes: instead of setting p and doing break, return it directly (that way the for loop will only finish if the id is not found), and change return p at the end into return NULL. 这可以通过进行以下两项更改来完成:而不是设置p并执行break,而是直接将其返回(这样,for循环将仅在未找到id的情况下完成),并将最后的return p更改为return NULL。

Then when making the recursive call, you need to check the return value. 然后,在进行递归调用时,您需要检查返回值。 If it was NULL, continue. 如果为NULL,则继续。 Otherwise return it. 否则返回它。

And the previous answer is correct that the check for the child id can better be removed, too, especially because it needs to (but doesn't) check for NULL. 前面的答案是正确的,因为也可以更好地删除对子ID的检查,尤其是因为它需要(但不需要)检查NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM