Java Program to Implement Trie

«
»
This is a Java Program to implement Trie. A trie is an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node, instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Values are normally not associated with every node, only with leaves and some inner nodes that correspond to keys of interest.

Here is the source code of the Java program to implement Trie. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  *  Java Program to Implement Trie
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. class TrieNode 
  8. {
  9.     char content; 
  10.     boolean isEnd; 
  11.     int count;  
  12.     LinkedList<TrieNode> childList; 
  13.  
  14.     /* Constructor */
  15.     public TrieNode(char c)
  16.     {
  17.         childList = new LinkedList<TrieNode>();
  18.         isEnd = false;
  19.         content = c;
  20.         count = 0;
  21.     }  
  22.     public TrieNode subNode(char c)
  23.     {
  24.         if (childList != null)
  25.             for (TrieNode eachChild : childList)
  26.                 if (eachChild.content == c)
  27.                     return eachChild;
  28.         return null;
  29.     }
  30. }
  31.  
  32. class Trie
  33. {
  34.     private TrieNode root;
  35.  
  36.      /* Constructor */
  37.     public Trie()
  38.     {
  39.         root = new TrieNode(' '); 
  40.     }
  41.      /* Function to insert word */
  42.     public void insert(String word)
  43.     {
  44.         if (search(word) == true) 
  45.             return;        
  46.         TrieNode current = root; 
  47.         for (char ch : word.toCharArray() )
  48.         {
  49.             TrieNode child = current.subNode(ch);
  50.             if (child != null)
  51.                 current = child;
  52.             else 
  53.             {
  54.                  current.childList.add(new TrieNode(ch));
  55.                  current = current.subNode(ch);
  56.             }
  57.             current.count++;
  58.         }
  59.         current.isEnd = true;
  60.     }
  61.     /* Function to search for word */
  62.     public boolean search(String word)
  63.     {
  64.         TrieNode current = root;  
  65.         for (char ch : word.toCharArray() )
  66.         {
  67.             if (current.subNode(ch) == null)
  68.                 return false;
  69.             else
  70.                 current = current.subNode(ch);
  71.         }      
  72.         if (current.isEnd == true) 
  73.             return true;
  74.         return false;
  75.     }
  76.     /* Function to remove a word */
  77.     public void remove(String word)
  78.     {
  79.         if (search(word) == false)
  80.         {
  81.             System.out.println(word +" does not exist in trie\n");
  82.             return;
  83.         }             
  84.         TrieNode current = root;
  85.         for (char ch : word.toCharArray()) 
  86.         { 
  87.             TrieNode child = current.subNode(ch);
  88.             if (child.count == 1) 
  89.             {
  90.                 current.childList.remove(child);
  91.                 return;
  92.             } 
  93.             else 
  94.             {
  95.                 child.count--;
  96.                 current = child;
  97.             }
  98.         }
  99.         current.isEnd = false;
  100.     }
  101. }    
  102.  
  103. /* Class Trie Test */
  104. public class TrieTest
  105. {
  106.     public static void main(String[] args)
  107.     {            
  108.         Scanner scan = new Scanner(System.in);
  109.         /* Creating object of AATree */
  110.         Trie t = new Trie(); 
  111.         System.out.println("Trie Test\n");          
  112.         char ch;
  113.         /*  Perform tree operations  */
  114.         do    
  115.         {
  116.             System.out.println("\nTrie Operations\n");
  117.             System.out.println("1. insert ");
  118.             System.out.println("2. delete");
  119.             System.out.println("3. search");
  120.  
  121.             int choice = scan.nextInt();            
  122.             switch (choice)
  123.             {
  124.             case 1 : 
  125.                 System.out.println("Enter string element to insert");
  126.                 t.insert( scan.next() );                     
  127.                 break;                          
  128.             case 2 : 
  129.                 System.out.println("Enter string element to delete");
  130.                 try
  131.                 {
  132.                     t.remove( scan.next() ); 
  133.                 }                    
  134.                 catch (Exception e)
  135.                 {
  136.                     System.out.println(e.getMessage()+" not found ");
  137.                 }
  138.                 break;                         
  139.             case 3 : 
  140.                 System.out.println("Enter string element to search");
  141.                 System.out.println("Search result : "+ t.search( scan.next() ));
  142.                 break;                                          
  143.             default : 
  144.                 System.out.println("Wrong Entry \n ");
  145.                 break;   
  146.             }
  147.  
  148.             System.out.println("\nDo you want to continue (Type y or n) \n");
  149.             ch = scan.next().charAt(0);                        
  150.         } while (ch == 'Y'|| ch == 'y');               
  151.     }
  152. }

advertisement
Trie Test
 
 
Trie Operations
 
1. insert
2. delete
3. search
1
Enter string element to insert
trie
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
1
Enter string element to insert
tree
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
1
Enter string element to insert
branch
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
1
Enter string element to insert
beach
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
bean
Search result : false
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
beach
Search result : true
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
2
Enter string element to delete
bean
bean does not exist in trie
 
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
2
Enter string element to delete
beach
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
beach
Search result : false
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
2
Enter string element to delete
tree
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
tree
Search result : false
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
trie
Search result : true
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
2
Enter string element to delete
trie
 
Do you want to continue (Type y or n)
 
y
 
Trie Operations
 
1. insert
2. delete
3. search
3
Enter string element to search
trie
Search result : false
 
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn