1
私のバイナリ検索ツリーは、3つ以上のノードを管理したり、表示できるようです。私はそれらを繰り返し追加し、割り当てでスタックを使用して表示する必要があったが、3つ以上の要素がある場合はBSTを表示するのに問題がある。バイナリ検索ツリーに3ノード以上表示されないのはなぜですか?
public boolean add(E b) {
//if tree is empty
if (root == null) {
root = new Node();
root.setValue(b);
count++;
return true;
} //if val is already in tree
else if (b.compareTo(root.getValue()) == 0) {
return false;
//if left or right spot is free
} else {
while (root != null) {
compareResult = root.value.compareTo(b);
spot = root;
if (compareResult < 0) {
if (root.left != null) {
spot = spot.left;
count++;
return true;
} else {
Node n = new Node<>();
n.setValue(b);
spot.left = n;
count++;
return true;
}
} else if (compareResult > 0) {
if (root.right != null) {
spot = spot.right;
count++;
return true;
} else {
Node n = new Node<>();
n.setValue(b);
spot.right = n;
count++;
return true;
}
} else {
return false;
}
}
}
return false;
}
public void display() {
//needs to use an iterator
if (root == null) {
System.out.println("Error");
} else {
Node CurrentNode;
CurrentNode = root;
while (!stack.isEmpty() || CurrentNode != null) {
if (CurrentNode != null) {
stack.push(CurrentNode);
CurrentNode = CurrentNode.right;
}
else {
Node m= stack.pop();
System.out.println(m.value);
CurrentNode = m.left;
}
}
}
}
public int size() {
return count;
}
@Override
public int compareTo(E t) {
return ordering.compare(root,t);
}
@Override
public int compare(E t, E t1) {
return t.compareTo(t1);
}
Nodeクラスは、この
public class Node<E extends Comparable> {
E value;
Node<E> left;
Node<E> right;
//constructor
public Node() {
value = null;
left = null;
right = null;
}
public void setValue(E t) {
value = t;
}
public void setLeft(Node<E> t) {
left = t;
}
public void setRight(Node<E> t) {
right = t;
}
public Node<E> getLeft() {
return left;
}
public Node<E> getRight() {
return right;
}
public E getValue() {
return value;
}
私はあなたの宿題をするつもりはないので、これは完全な答えではありません。しかし基本的には、あなたの 'add'メソッドは再帰的である必要があります。それは、ノードのルート、左の子、または右の子にのみ追加します。あなたのロジックの多くは削除することができます。挿入している値がルートの値より_ _値が小さい場合は、左側のノードを再び通過するだけで 'add'を呼び出すことができます。ルートの値よりも大きい場合は、右側のノードを再び渡して 'add'を呼び出すことができます。この再帰的なステップがありません。 –
私はそれを再帰的にどのように呼びますか? BST内のほとんどのオブジェクトはNodeオブジェクトなので、もう一度addを呼び出すことはできません。私はプログラムを終了する方法を知らないだろうEでのみ追加を呼び出すことができます。 – HollyNeedsHelp
いくつかのオプションがあります。 'add'メソッドを' Node'クラスに入れることができます。次に 'Tree'クラスの' add'メソッドは、 'Node'が存在するかどうかをチェックし、' Node'が存在すれば 'add'を呼び出します。代わりに、 'Node'クラスの中の' left'と 'right'が実際にはノードではなくツリーであるようにすることもできます。 –