我的节点类
package kth.id2010.lab.lab04;
public class Node {
boolean isLeaf = false;
int numberOfKeys;
String[] keys = new String[2]; //each node can contain up to 2 keys
int[] key1Values = new int[2]; //every key contains 2 values
int[] key2Values = new int[2]; //every key contains 2 values
Node[] subtrees = new Node[3]; //every node can contain pointers to 3 different nodes
Node[] parent = new Node[1]; //every node contains a pointer to a parent node, if root parent is null
Node(Node n) {
n.numberOfKeys = 0;
n.isLeaf = true;
}
}
我的树类
package kth.id2010.lab.lab04;
public class Tree {
Node root; // root node of the tree
int n; // number of elements in the tree
private Tree(){
root = new Node(root);
n = 0;
root.parent = null;
}
//Return the values of the key if we find it
public int[] get(Node n, String key){
if(n.isLeaf){
if(n.keys[0].equals(key)){
return(n.key1Values);
}
else if(n.keys[1].equals(key)){
return(n.key2Values);
}
else{
return null;
}
}
else if(key.length() < n.keys[0].length()){
return(get(n.subtrees[0],key));
}
else if(n.numberOfKeys == 2 && key.length() < n.keys[1].length()){
return(get(n.subtrees[1],key));
}
else{
return(get(n.subtrees[2],key));
}
}
//put new values to the key
public void put(Node n, int[] value, String key){
if(n.keys[0].equals(key)){
n.key1Values = value;
}
else if(n.keys[1].equals(key)){
n.key2Values = value;
}
else if(n.keys[0].length() < key.length()){
put(n.subtrees[0],value,key);
}
else if(n.numberOfKeys == 2 && n.keys[1].length() < key.length()){
put(n.subtrees[1],value,key);
}
else{
put(n.subtrees[2],value,key);
}
}
public int size(){
return(this.n);
}
}
我的驱动程序类
package kth.id2010.lab.lab04;
import edu.princeton.cs.introcs.In;
import java.net.URL;
public class Driver {
public static void main(String[] args) {
URL url = Driver.class.getResource("/kap1.txt");
System.out.println(System.getProperty("user.dir"));
In input = new In(url);
String[] usedWords;
while(!input.isEmpty()){
String line = input.readLine().trim();
String[] words = line.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
}
因此,对于我的作业,words
中的每个单词都是1个键,keyValue1[0]
是words
中的出现次数=索引,keyValue1[1]
是出现次数。所以我的想法是,对于words
中的每个单词,我将它添加到节点并添加索引号作为第一个值,然后我将单词添加到usedWords
并检查该单词的次数是多少次在words
。我唯一坚持的是如何将它添加为节点并尝试对其进行排序,并将更大的节点作为其父节点。