2010-04-04 9 views
0

모든 데이터 유형으로 구성 할 수있는 일반 BST를 만들고 싶지만 내 BST가 일반적인 경우 트리에 추가 할 수있는 방법이 확실하지 않습니다. 내 필요한 코드는 모두 아래에 있습니다. Locations로 구성된 내 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

+2

영감을 얻으려면 이것 (java.util.Collections.binarySearch (List >, T) 어때? – Adi

답변

6

코드 Comparable<? super E> 구현 :

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

는 그런 다음 compareTo를 호출 할 수

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

(등)

또는 검색 트리가 생성 될 때 Comparator<E>으로 호출자를 전달한 다음이를 사용하여 요소를 비교할 수 있습니다. 이것은 실제로 더 유연한 솔루션입니다. 즉, 동일한 요소 유형에 대해 서로 다른 이진 검색 트리를 만들 수 있지만 여러 가지 방법으로 정렬 할 수 있습니다.