number of nodes in trie node
Here, I have created a class Trie and TrieNode, that implements Trie data structure in Java. I have a task to write a method called size() [return type int] to return the number of nodes in the Trie.
class Trie {
private TrieNode root;
/////////////////////
// TrieNode class
class TrieNode {
public char c;
public boolean isWord;
public TrieNode[] children;
public TrieNode(char c) {
this.c = c;
isWord = false;
children = new TrieNode[26];
}
}
public Trie() {
root = new TrieNode('\0');
}
public boolean isPrefix(String word) {
return getNode(word) != null;
}
public void insert(String word) {
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (curr.children[c - 'A'] == null)
curr.children[c - 'A'] = new TrieNode(c);
curr = curr.children[c - 'A'];
}
curr.isWord = true;
}
// Helper
private TrieNode getNode(String word) {
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (curr.children[c - 'A'] == null)
return null;
curr = curr.children[c - 'A'];
}
return curr;
}
I have been trying to get the number of nodes in the Trie, and what I was thinking about is:
public int size() {
return size(root);
}
private int size(TrieNode root) {
for (int i = 0; i < root.children.length; i++) {
if (root.children[i] != null) {
if (root.isWord)
return 1;
else
return 1 + size(root.children[i]);
}
}
return 0;
}
But it is not right. Any ideas?
from Recent Questions - Stack Overflow https://ift.tt/3FLYjP9
https://ift.tt/eA8V8J
Comments
Post a Comment