【问题标题】:Fail to set the isLeaf flag in Trie在 Trie 中设置 isLeaf 标志失败
【发布时间】:2021-05-10 01:34:23
【问题描述】:

在这个简单的应用程序中,我正在构建一个包含两个单词的树——“abb”和“abbbb”。无法为“abb”设置isLeaf,因为“abb”之后没有打印“should print isLeaf”。

这里缺少什么?

class Trie{
    boolean isLeaf=false;
    Trie[] children=new Trie[26];
    
    Trie(){       
    }
}

class Test 
{ 
        static void printTrie(Trie trie, int p){
            if(trie==null)
                return;
            
            System.out.println((char)(p+'a'));
            if(trie.isLeaf)
                System.out.println("should print isLeaf");            
            
            for(int i=0;i<26;i++){
                if(trie.children[i]!=null)
                    printTrie(trie.children[i], i);
            }
        }

        // Driver program
        public static void main(String args[])
        {
            String[] words=new String[] {"abb","abbbb"};
            Trie trie=new Trie();
            for(var w:words){  
                Trie curr=trie;
                for(var c:w.toCharArray()){
                    curr.children[c-'a']=new Trie();
                    curr=curr.children[c-'a'];
                    System.out.println(c);
                }
                System.out.println("isLeaf");
                curr.isLeaf=true;
            }           
            printTrie(trie, -1);
        }
} 

【问题讨论】:

  • 缺少行:if(curr.children[c-'a']==null) 行后:for(var c:w.toCharArray()){

标签: java trie


【解决方案1】:

与其在 for 循环的第一行将新的 Trie 分配给 curr.children,不如先检查它是否存在,然后重用现有的子项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多