Skip to content

Commit 2522c37

Browse files
authored
Create Insertion in Trie.java
1 parent b420a1c commit 2522c37

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Trie/Insertion in Trie.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class Main
2+
{
3+
// represt every single node of the trie
4+
static class Node{
5+
Node[] children; // 26
6+
boolean endOfWord;
7+
8+
public Node(){
9+
children = new Node[26]; // a to z
10+
// initializing Array
11+
for(int i = 0; i < 26; i++){
12+
children[i] = null; // because an object us being created of class node so allocating slight memory is imp. otherwise we will get error
13+
}
14+
endOfWord = false; // initializing
15+
}
16+
}
17+
18+
static Node root = new Node();
19+
20+
21+
// till now we have defined trie data structure
22+
// now we will start storing data in it
23+
24+
25+
//INSERTION IN TRIE
26+
public static void insert(String singleWordFromArray){
27+
for(int i = 0; i < singleWordFromArray.length(); i++){
28+
int index = singleWordFromArray.charAt(i) - 'a';
29+
if(root.children[index] == null){
30+
// add new Node
31+
root.children[index] = new Node();
32+
}
33+
if(i == singleWordFromArray.length() - 1){
34+
root.children[index].endOfWord = true;
35+
}
36+
root = root.children[index];
37+
}
38+
}
39+
40+
public static void main(String[] args) {
41+
String words[] = {"the", "a", "there", "their", "any"};
42+
43+
for(int i = 0; i < words.length; i++){
44+
insert(words[i]);
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)