Ich habe einen sehr einfachen binären Baum zu implementieren. Ich brauche nur eine put
und eine get
Methode. Wenn ein Schlüssel bereits verwendet wird, muss nur der Wert ersetzt werden. Dies ist mein Code, aber ich bin sehr, sehr unsicher, ob dies richtig funktioniert ... können Sie bestätigen, dass dieser Code funktioniert? Entschuldigung ... ich weiß nicht, wie man solch eine Klasse debuggt ...:/Und nein - es ist keine Hausaufgabe. Nur eine Vorlage aus einem Kurs Java zu lernen ...;)Einfache Binary Tree in Java in nur eine Klasse
//Don't import any other classes.
public class BinaryTree<K extends Comparable<K>, V> {
//Please don't add any further attributes.
private K key;
private V value;
private BinaryTree<K, V> left;
private BinaryTree<K, V> right;
/**
* This class is a binary tree-based collection for key-value-pairs.
*/
public static void main(String[] args) {
BinaryTree<Integer, String> treeInteger = new BinaryTree<>(2, "two ");
treeInteger.put(1, "one ");
treeInteger.put(0, "zero ");
treeInteger.put(3, "three ");
treeInteger.put(6, "six ");
treeInteger.put(3, "threeNew ");
System.out.println(tree.toString());
if (tree.get(4) == null) {
System.out.println("null");
}
}
public BinaryTree(K key, V value) {
//Fill in your solution here.
this.key = key;
this.value = value;
}
public void put(K key, V value) {
//Fill in your solution here.
if (this.key.compareTo(key) > 0) {
// links
if (this.left == null) {
this.left = new BinaryTree<>(key, value);
} else {
left.put(key, value);
}
} else if (this.key.compareTo(key) < 0) {
if (this.right == null) {
this.right = new BinaryTree<>(key, value);
} else {
this.right.put(key, value);
}
} else if (this.key.compareTo(key) == 0) {
this.key = key;
this.value = value;
}
}
public V get(K key) {
//Fill in your solution here.
if (this.key.compareTo(key) > 0 && this.left != null) {
return this.left.get(key);
} else if (this.key.compareTo(key) < 0 && this.right != null) {
return this.right.get(key);
} else if (this.key.compareTo(key) == 0 && this.value != null) {
return this.value;
} else if (this.key == key) {
return value;
}
return null;
}
}
Mein eigenen touring
String s = "";
if (left != null) {
s += left.toString();
}
if (value != null) {
s += value.toString();
}
if (right != null) {
s += right.toString();
}
return s;
Warum Sie es nicht laufen? –
Fügen Sie einige if-Anweisungen in der Hauptmethode hinzu, die sicherstellen, dass verschiedene Punkte im Baum die richtigen Schlüssel und Werte haben. Einfach – SamTebbs33
@ TungD.Nguyen, weil ich nicht wissen kann, wie man debuggt ... Entweder meine 'toString' ist nicht korrekt oder meine Klasse .. – Tobias