여기서 내가 만든 클래스 라고 TrieNode,를 구현하는 라 데이터 구조에서 Java. 나는 작업을 쓰는 방법이라고 크기()[익 유형 int]을 수의 노드에서 라.
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;
}
려고 노력했습을 얻을 수의 노드 트리,그리고 무엇에 대해 생각하고 있었다:
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;
}
하지만 그것을 옳지 않다. 어떤 아이디어가?