I am trying the insertion operation in a Trie and a read operation for the below implementation I am having trouble with insertion. I don't think there's is any problem with the reading operation. In my case, each node of Trie has an array of node pointers and a value field. Also, I am marking each character insertion theoretically each node has uppercase char and an integer value. For example: say 3 strings are to be added given as ATAGA, ATC, and GAT so each of the characters has a value which will be given by the "pass" variable in the code, see expected output for more details.
import java.util.*;
class node{
public int val;
public node ptrs[];
node(){
this.val =0;
ptrs = new node[26];
for (node ptr : ptrs) {
ptr = null;
}
}
}
class Tree{
public node root = new node();
public int pass =0;
void insert(String s) {
node trv = root;
for (int i = 0; i < s.length(); i++) {
if (trv.ptrs[s.charAt(i) - 'A'] == null) {
trv.ptrs[s.charAt(i) - 'A'] = new node();
trv.val = ++pass;
// System.out.println(s.charAt(i)+" val : "+trv.val);
}
trv = trv.ptrs[s.charAt(i) - 'A'];
}
}
private void visit(node trv){
for(int i =0;i<26;i++){
if(trv.ptrs[i]!=null){
System.out.println((char)(i+'A')+" : "+trv.val);
visit(trv.ptrs[i]);
}
}
}
void call(){
this.visit(root);
}
}
public class trie {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Tree t = new Tree();
while (n-- > 0) {
String s = sc.next();
t.insert(s);
}
t.call();
sc.close();
}
}
my output :
3
ATAGA
ATC
GAT
A : 7
T : 2
A : 6
G : 4
A : 5
C : 6
G : 7
A : 8
T : 9
expected output :
3
ATAGA
ATC
GAT
A : 1
T : 2
A : 3
G : 4
A : 5
C : 6
G : 7
A : 8
T : 9
I have tested the changes and I can see the expected output as you mentioned.
You have to update the children nodes val and ptrs array not the parent during the insertion.
for (int i = 0; i < s.length(); i++)
{
if (trv.ptrs[s.charAt(i) - 'A'] == null)
{
trv.ptrs[s.charAt(i) - 'A'] = new node();
trv.ptrs[s.charAt(i) - 'A'].val = ++pass;
}
}
Similarly during the search/visit, fetch the value from the child node of the current node.
for(int i=0;i<26;i++)
{
if(trv.ptrs[i]!=null)
{
System.out.println((char)(i+'A')+" : "+trv.ptrs[i].val);
visit(trv.ptrs[i]);
}
}