2010-04-04 40 views
0

我想打一個通用的BST,可以由任何數據類型的,但我不知道我能怎麼的東西添加到樹,如果我的BST是通用的。我所需的全部代碼如下。我希望我的BST由位置,並通過X變量進行排序。任何幫助表示讚賞。二叉搜索樹在Java中

主要感謝尋找。

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); 
    } 


} 
+0

這聽起來像功課給我。 – Avitus 2010-04-04 17:48:06

+2

這個(java.util.Collections.binarySearch(List <?extends Comparable >,T))如何啓發? – Adi 2010-04-04 17:49:44

回答

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>,然後使用它來比較元素。在我看來,這實際上是一個更靈活的解決方案 - 這意味着您可以爲相同的元素類型創建不同的二叉搜索樹,但是以不同的方式對它們排序。