【问题标题】:Tiers tree print all suffixed provied wrong output层树打印所有提供错误输出的后缀
【发布时间】:2017-04-17 10:20:05
【问题描述】:

我需要打印轮胎树的所有后缀。我正在使用以下遍历方法打印所有后缀。

struct TrieNode {
    struct TrieNode *children[ALPHABET_SIZE];
    char label;
    bool isLeaf;
};

void traverse(char prefix[], struct TrieNode *root) {
    concatenate_string(prefix, &(root->label));
    if (root->isLeaf) {
        printf("%s\n", prefix);
    }

    for (int i = 0; i < 26; i++) {
        if (root->children[i]) {
            traverse(prefix, root->children[i]);
        }
    }
}

考虑遵循 Trie 树

    Root
 |     |    |
 L     M    N
|  |
a  b 

所以我的预期输出是

La
Lb
M
N

但是我的代码打印出来了

  La
  Lab
  LabM
  LabMN

据我了解,问题的根本原因是没有正确更新前缀变量。如何解决这个问题?

【问题讨论】:

  • 我认为prefix需要重置或使用复制。
  • 是的,我觉得使用副本就可以了。我该怎么做?
  • Paul Ogilvie 已经提出了制作副本的建议。为了重置,记住prefix的结尾并告诉concatenate_string加入的地方。
  • void traverse(char prefix[], struct TrieNode *root, int depth) { prefix[depth] = root-&gt;label; prefix[depth+1] = 0;...traverse(prefix, root-&gt;children[i], depth+1);

标签: c algorithm trie


【解决方案1】:

那是因为你一直在连接。最好将char prefix[] 作为局部变量,例如:

void traverse(char prefix[], struct TrieNode *root)
{
    char newprefix[30];
    strcpy(newprefix, prefix);
    concatenate_string(newprefix, &(root->label));
    if (root->isLeaf) {
        printf("%s\n",newprefix);
    }

    for(int i=0 ; i< 26 ; i++){
        if(root->children[i]){
            traverse(newprefix, root->children[i]);
        }
    }
}

然后像这样调用:

traverse("", root);

【讨论】:

  • 如果我们作为局部变量使用,如何递归传递
猜你喜欢
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多