public class BinarySearchTree<E extends Comparable<E>> implements BinaryTree<E>
{
BinaryTree<E> left = new EmptyBinarySearchTree<E>();
BinaryTree<E> right = new EmptyBinarySearchTree<E>();
E value;
public BinarySearchTree (E value){
this.value = value;
}
public boolean containsKey(E value){
boolean result = false;
int cmp = value.compareTo(this.value);
if(cmp == 0)
result = true;
if(cmp < 0)
result = left.containsKey(value);
if(cmp > 0)
result = right.containsKey(value);
return result;
}
public BinaryTree<E> add(E value){
int cmp = value.compareTo(this.value);
if(cmp<0)
left = left.add(value);
if(cmp>0)
right = right.add(value);
return this;
}
public E get(E value){
int cmp = value.compareTo(this.value);
if(cmp == 0) return this.value;
if(cmp < 0) return left.get(value);
if(cmp > 0) return right.get(value);
return this.value;
}
public BinaryTree<E> getLeft(){
return left;
}
public BinaryTree<E> getRight(){
return right;
}
public E getValue(){
return value;
}
/**
* Change the value of this BinaryTree to the given value
*/
public void setValue(E value){
this.value = value;
}
/**
* Set the left child of this BinaryTree to the given BinaryTree
*/
public void setLeft(BinaryTree<E> left){
this.left = left;
}
/**
* Set the right child of this BinaryTree to the given BinaryTree
*/
public void setRight(BinaryTree<E> right){
this.right = right;
}
public String toPreOrderString(){
String result = "" + value + ",";
result += left.toPreOrderString();
result += right.toPreOrderString();
return result;
}
Problem ist mit toPreOrderString()
Methode. Zum Beispiel, wenn ich rufe diese Methode auf einen bestimmten Satz von Daten erhalte ich folgende Ausgabe:Probleme beim Drucken von Werten von BinarySearchTree in Vorbestellung Traversal
kimmy,jimmy,al,[][]joe,jo,[][][]susie,sue,[][][]
Wie kann ich einstellen, meine Methode die Ausgabe wie folgt aussehen zu machen:
[kimmy,jimmy,al,joe,jo,susie,sue]
ich kann tu es raus. Bitte hilfe.
in 'toPreOrderString()' überprüfen Sie links und rechts, wenn einer ist 'instanceof EmptyBinarySearchTree', und wenn einer ist, nicht an die Ausgabe anhängen. –