Getting a list of words from a Trie

后端 未结 10 1013
野性不改
野性不改 2021-01-02 15:29

I\'m looking to use the following code to not check whether there is a word matching in the Trie but to return a list all words beginning with the prefix inputted by the use

10条回答
  •  感动是毒
    2021-01-02 15:35

    The below recursive code can be used where your TrieNode is like this: This code works fine.

    TrieNode(char c)
    {
    
            this.con=c;
            this.isEnd=false;
            list=new ArrayList();
            count=0;
    
    }
    
    //--------------------------------------------------
    
    public void Print(TrieNode root1, ArrayList path)
    {
    
          if(root1==null)
              return;
    
          if(root1.isEnd==true)
          {
              //print the entire path
              ListIterator itr1=path.listIterator();
              while(itr1.hasNext())
              {
                  System.out.print(itr1.next());
              }
              System.out.println();
              return;
          }
          else{
              ListIterator itr=root1.list.listIterator();
              while(itr.hasNext())
              {
                  TrieNode child=itr.next();
                  path.add(child.con);
                  Print(child,path);
                  path.remove(path.size()-1);
    
                }
          }
    

提交回复
热议问题