2015-11-20 2 views
0

Я пытаюсь реализовать метод вставки структуры данных Patricia Trie, но у меня есть ощущение, что я написал много строк кода. Пожалуйста, скажите мне, где я могу позвонить методу insert(TrieNode nodeRoot, String s) rekursiv?метод вставки структуры данных Trie

Код:

private void insert(TrieNode nodeRoot, String s) { 

    int len1 = nodeRoot.value.length(); 
    int len2 = s.length(); 
    int len = Math.min(len1, len2); 

    for (int index = 0; index < len; index++) { 
     if (s.charAt(index) != nodeRoot.value.charAt(index)) { 

      // In case the both words have common substrings and after the 
      // common substrings the words are split. 
      String samesubString = s.substring(0, index); 
      String substringSplit1 = nodeRoot.value.substring(index); 
      String substringSplit2 = s.substring(index); 
      if (!samesubString.isEmpty()) { 
       nodeRoot.value = samesubString; 
      } 

      TrieNode nodeLeft = new TrieNode(substringSplit1); 
      nodeLeft.isWord = true; 
      TrieNode nodeRight = new TrieNode(substringSplit2); 
      nodeRight.isWord = true; 

      if (nodeRoot.getNext() != null && !nodeRoot.getNext().isEmpty()) { 
       checkTheValieAvialable(nodeRoot, s, nodeRight); 

      } else { 
       nodeRoot.next.add(nodeLeft); 
       nodeRoot.next.add(nodeRight); 
       for (TrieNode subword : nodeRoot.getNext()) { 
        System.out.println(nodeRoot.getValue() + "---" 
          + subword.getValue()); 
       } 
      } 

      break; 

     } else if (index == (s.length() - 1) 
       || index == (nodeRoot.value.length() - 1)) { 
      // In case the node just needs one path since one word is 
      // substring of the other. 
      // For example (aba and abac) 

      if (len1 > len2) { 
       // root value is longer 
       System.out.println("root value is longer"); 

       String samesubString = nodeRoot.value.substring(0, 
         index + 1); 
       String different = nodeRoot.value.substring(index + 1); 

       if (nodeRoot.getNext() != null 
         && !nodeRoot.getNext().isEmpty()) { 
        for (TrieNode subword : nodeRoot.getNext()) { 
         String subword2 = subword.getValue(); 
         boolean contains = different.contains(subword2); 
         if (contains) { 
          String[] split = different.split(subword2); 
          TrieNode leaf1 = new TrieNode(split[1]); 
          leaf1.isWord = true; 
          subword.next.add(leaf1); 
          System.out.println("Test."); 

         } 

        } 
       } else { 

        String substringSplit1 = nodeRoot.value.substring(index + 1); 
        nodeRoot.value = samesubString; 
        TrieNode leaf = new TrieNode(substringSplit1); 
        leaf.isWord = true; 
        nodeRoot.next.add(leaf); 

        for (TrieNode subword : nodeRoot.getNext()) { 
         System.out.println(nodeRoot.getValue() + "---" 
           + subword.getValue()); 
        } 

       } 

       String substringSplit1 = nodeRoot.value 
         .substring(index + 1); 

       nodeRoot.value = samesubString; 
       nodeRoot.isWord = true; 
       TrieNode leaf = new TrieNode(substringSplit1); 
       leaf.isWord = true; 
       nodeRoot.next.add(leaf); 

       for (TrieNode subword : nodeRoot.getNext()) { 
        System.out.println(nodeRoot.getValue() + "---" 
          + subword.getValue()); 
       } 

      } else { 
       // new inserted string value is longer. For example (abac and aba). 
       System.out.println("instered is longer"); 

       String samesubString = s.substring(0, index + 1); 
       String different = s.substring(index + 1); 
       if (nodeRoot.getNext() != null 
         && !nodeRoot.getNext().isEmpty()) { 
        for (TrieNode subword : nodeRoot.getNext()) { 
         String subword2 = subword.getValue(); 
         boolean contains = different.contains(subword2); 
         if (contains) { 
          String[] split = different.split(subword2); 
          TrieNode leaf1 = new TrieNode(split[1]); 
          leaf1.isWord = true; 
          subword.next.add(leaf1); 
          System.out.println("Test."); 

         } 

        } 
       } else { 

        String substringSplit1 = s.substring(index + 1); 

        s = samesubString; 
        TrieNode parentLeaf = new TrieNode(s); 
        parentLeaf.isWord = true; 

        TrieNode leaf = new TrieNode(substringSplit1); 
        leaf.isWord = true; 
        nodeRoot.next.add(leaf); 

        for (TrieNode subword : nodeRoot.getNext()) { 
         System.out.println(nodeRoot.getValue() + "---" 
           + subword.getValue()); 
        } 

       } 

      } 

     } else { 

      System.out.println("They are the same - " + index); 

     } 

    } 

} 

класс TrieNode:

package patriciaTrie; 

import java.util.ArrayList; 

public class TrieNode { 


    ArrayList<TrieNode> next = new ArrayList<TrieNode>(); 
    String value; 
    boolean isWord; 

    TrieNode(String value){ 
     this.value = value; 

    } 

    public ArrayList<TrieNode> getNext() { 
     return next; 
    } 

    public void setNext(ArrayList<TrieNode> next) { 
     this.next = next; 
    } 

    public String getValue() { 
     return value; 
    } 

    public void setValue(String value) { 
     this.value = value; 
    } 
} 

ответ

1

При использовании рекурсии пожалуйста рассмотрим шаги:

  1. Base состояние
  2. Логика (если имеется)
  3. Рекурсивный вызов.

Исх. для факториала числа:

int fact(int n) 
{ 
    if(n==0 || n==1) 
    return 1; // Base condition 
    return n * fact(n-1); // Recursive call 
} 

Применяя ту же концепцию в TRIE:

  1. баз условия: во время прохождения через путь, если мы достигли лист, текущая строка не в синтаксическом дереве, а затем создать новый край или узел и добавить к нему оставшийся символ.
  2. Рекурсивно вызывать вставку, если мы нашли соответствующий узел. И если соответствующий узел не существует, создайте новый путь с общим родителем.

Вы можете принять помощь от ссылки: http://www.geeksforgeeks.org/trie-insert-and-search/

Лучший способ подойти к проблеме рекурсивно, чтобы определить базовое условие в задаче.

Смежные вопросы