未能在 Trie 中设置 isLeaf 标志

Fail to set the isLeaf flag in Trie

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

这里缺少什么?

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);
        }
} 

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