[英]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.