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;
}
問題はtoPreOrderString()
メソッドで問題です。私は、データの特定のセットに、このメソッドを呼び出したときにたとえば、私は次のような出力が得られます。BinarySearchTreeの値をプリオーダートラバーサルで印刷する際の問題
kimmy,jimmy,al,[][]joe,jo,[][][]susie,sue,[][][]
私は、出力は次のように見えるように私の方法を調整することができます方法:
[kimmy,jimmy,al,joe,jo,susie,sue]
私ができますそれを把握していない。助けてください。
の 'toPreOrderString()'が 'instanceof EmptyBinarySearchTree'であれば左右にチェックし、もしあればそれを出力に追加しないでください。 –