0

我想制作一个通用的 BST,它可以由任何数据类型组成,但是如果我的 BST 是通用的,我不确定如何将内容添加到树中。我需要的所有代码都在下面。我希望我的 BST 由 Locations 组成,并按 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)

(ETC)

或者,您可以强制调用者在Comparator<E>构建搜索树时传入 a,然后使用它来比较元素。在我看来,这实际上是一个更灵活的解决方案——这意味着您可以为相同的元素类型创建不同的二叉搜索树,但以不同的方式对它们进行排序。

于 2010-04-04T17:59:49.073 回答