我被分配了创建一个 2-3 搜索树的任务,该树应该支持几个不同的操作,每个操作都分为任务的不同阶段。对于第 1 阶段,我应该支持操作 get、put 和 size。我目前正在尝试实现 get 操作,但我被卡住了,我无法思考如何继续,所以我质疑我编写的所有代码,并且觉得需要其他人的输入。
我已经查看了如何开发 2-3 搜索树,但我发现很多代码对我来说毫无意义,或者它只是没有做我需要它做的事情,我想尝试为我的从头开始,我们现在就在这里。
我的节点类
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[] values = new int[2]; //every key contains 2 values
Node[] subtrees = new Node[3]; //every node can contain pointers to 3 different nodes
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;
}
//Return the values of the key if we find it
public int[] get(String key){
//if the root has no subtrees check if it contain the right key
if(this.root.subtrees.length == 0){
if(this.root.keys[0] == key){
return(this.root.keys[0].values);
}
else if(this.root.keys[1] == key){
return(this.root.keys[1].values);
}
}
//if noot in root, check its subtree nodes
//and here I can't get my head around how to traverse down the tree
else{
for(int i = 0; i < this.root.subtrees.length; i++){
for(int j = 0; j < this.root.subtrees[i].keys.length; j++){
if(this.root.subtrees[i].keys[j] == key){
return(this.root.subtrees[i].keys[j].values);
}
}
}
}
return null;
}
}
我可以告诉自己的是,我需要找到一种方法来绑定values[]
每个键,但我不知道如何做。可能是睡眠不足,或者我陷入了这种思维方式。