【问题标题】:Traversing a Trie遍历 Trie
【发布时间】:2019-05-02 19:30:32
【问题描述】:

我正在尝试在 Java 中以 preorder 遍历 trie。如果我找到一片叶子,我需要做一些操作。我用树的根和一个空字符串“”调用方法,我可以进入递归。我在每个节点中都存储了一个字符串,并将单词标记为叶子。例如,“the”将通过以下节点找到:“”-->“t”-->“th”-->“the”。这就是我到目前为止所拥有的:

void traverse(TrieNode current, String prefix){
  for (TrieNode temp : current.getChildren()) {
                if (temp == null) continue;
                String s = temp.getKey();
                traverse(temp, s);
                if (temp.getIsLeaf()) {
                   //do operations
                }
   }
}

谁能帮我找到一个可行的解决方案?

【问题讨论】:

    标签: java trie


    【解决方案1】:

    预购意味着您首先访问根,然后是子级。我不明白你对String prefix 的使用(无论如何都可以通过current.getKey() 获得)

    void traverse(TrieNode current, String prefix){
      // do what you need with the key...
      String currentValue = current.getKey();
      // do what you need if leaf
      if (current.getIsLeaf()) {
        // do operations
      }
      for (TrieNode temp : current.getChildren()) {
          traverse(temp);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 2010-10-16
      • 2011-03-16
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多