[英]Binary Search Tree in Java
我想制作一个通用的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);
}
}
您可以限制您的类型以实现Comparable<? super E>
Comparable<? super E>
:
public class BinarySearchTree<E extends Comparable<? super E>>
然后,您可以调用compareTo
:
// Instead of if (element < root)
if (element.compareTo(root) < 0)
(等等)
另外,您可以在构造搜索树时强制调用者传递Comparator<E>
,然后使用它来比较元素。 在我看来,这实际上是一种更为灵活的解决方案-这意味着您可以为相同的元素类型创建不同的二进制搜索树,但是可以以不同的方式对其进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.