In this section we shall see how the insert() method on the TRIE data structure works. We shall take a specific case and analyze it with pictorial representation.
Before we begin, assume we already have an existing TRIE as shown below.
Lets see the steps on how to insert a word "bate". Any insertion would ideally be following the below algorithm.
- If the input string length is zero, then set the marker for the root node to be true.
- If the input string length is greater than zero, repeat steps 3 and 4 for each character
- If the character is present in the child node of the current node, set the current node point to the child node.
- If the character is not present in the child node, then insert a new node and set the current node to that newly inserted node.
- Set the marker flag to true when the end character is reached.
public void insert(String s){ Node current = root; if(s.length()==0) //For an empty character current.marker=true; for(int i=0;i<s.length();i++){ Node child = current.subNode(s.charAt(i)); if(child!=null){ current = child; } else{ current.child.add(new Node(s.charAt(i))); current = current.subNode(s.charAt(i)); } // Set marker to indicate end of the word if(i==s.length()-1) current.marker = true; } }
Now lets see how the word "bate" is getting inserted. Since the word "bate" is having length greater than zero, we can start inspecting each word.
- See whether "b" is present in the current node's children (which is root). Yes its present, so set the current node to the child node which is having the character "b".
- See whether "a" is present in the current node's children. Yes its present, so set the current node to the child node which is having the character "a".
- See whether "t" is present in the current node's children. Yes its present, so set the current node to the child node which is having the character "t".
- See whether "e" is present in the current node's children. No, its not present, so create a new node with character set to "e". Since "e" is the end of the word, set the marker flag to true.
The above picture shows how the word "bate" is inserted into the existing TRIE data structure. This example clearly shows how the insertion in a TRIE happens.
We shall take a look on the Search operation in the next part.
Cheers,
Bragaadeesh.
4 comments:
very good explanation
@n, thank you for reading !
We were just googling to see how to insert into a trie.. Yur site came up.. Great explanation Braga ! Awesome :)
- Div and KS
@div: what are the odds :) thanks for stopping by..
Post a Comment