0

任意のデータ型で構成できる汎用BSTを作成したいのですが、BSTが汎用である場合、ツリーに追加する方法がわかりません。必要なコードはすべて以下のとおりです。BSTをロケーションで構成し、x変数でソートする必要があります。どんな助けでも大歓迎です。

見てくれてありがとう。

public void add(E element)
{
    if (root == null)
         root = element;
    if (element < root)
         add(element, root.leftChild);
    if (element > root)
         add(element, root.rightChild);
    else
         System.out.println("Element Already Exists");
}

private void add(E element, E currLoc)
{
    if (currLoc == null)
         currLoc = element;
    if (element < root)
         add(element, currLoc.leftChild);
    if (element > root)
         add(element, currLoc.rightChild);
    else
         System.out.println("Element Already Exists);
}

その他のコード

public class BinaryNode<E>
{
    E BinaryNode;
    BinaryNode nextBinaryNode;
    BinaryNode prevBinaryNode;

    public BinaryNode()
    {
        BinaryNode = null;
        nextBinaryNode = null;
        prevBinaryNode = null;
    }

}


public class Location<AnyType> extends BinaryNode
{
    String name;
    int x,y;

    public Location()
    {
        name = null;
        x = 0;
        y = 0;
    }

    public Location(String newName, int xCord, int yCord)
    {
        name = newName;
        x = xCord;
        y = yCord;
    }

    public int equals(Location otherScene)
    {
        return name.compareToIgnoreCase(otherScene.name);
    }


}
4

1 に答える 1

6

型を実装するように制約できますComparable<? super E>

public class BinarySearchTree<E extends Comparable<? super E>>

次に、次のように呼び出すことができますcompareTo

// Instead of if (element < root)
if (element.compareTo(root) < 0)

(等)

または、検索ツリーが構築されるときに呼び出し元に a を渡すように強制し、Comparator<E>それを使用して要素を比較することもできます。私の見解では、これは実際にはより柔軟なソリューションです。つまり、同じ要素タイプに対して異なるバイナリ検索ツリーを作成できますが、それらを異なる方法で並べることができます。

于 2010-04-04T17:59:49.073 に答える