2014-07-19 64 views
0

我正在學習二叉搜索樹並試圖用Java實現它。比較已經實現可比較的類的對象

public class BinarySearchTree<T> 
    { 
     private class Node 
     { 
      public T data; 
      public Node left; 
      public Node right; 
     } 

     //some code goes here 

     public void insert(T data) 
     { 
      //make a new node and add data to that node 
      //call to recursive function 
     } 
     private Node ins(Node root,Node toBeInserted) 
     { 
      if(root==null) { root = tobeInserted; return root; } 

      //problem is here... 
      else if(toBeInserted.data<=root.data)// <----How to do this ????? 
       root = ins(root.left,toBeInserted); 
      else 
       root = ins(root.right,toBeInserted); 
      return root; 
     } 
     //some more code 
    } 

問題是如何比較類T的對象? 如果我在某個T類中實現了可比較的話,那麼如何比較存儲在左右節點中的數據?

在此先感謝。

回答

2

如果T始終貫徹Comparable,您可以添加相應的綁定到它的定義:

public class BinarySearchTree<T extends Comparable<T>> { ... } 

那麼你可以使用compareTo()

toBeInserted.data.compareTo(root.data) <= 0 
+0

如果T已經實現了許多接口,並且在像上面這樣的其他類中需要至少兩個不同接口的函數,那麼?? – SPK

+0

是否SomeClass ?這似乎不可能 – SPK

+0

'T擴展InterFace1&InterFace2' – axtavt

0

使類定義

然後插入

嘗試了這一點

/** 
    * This method inserts new node in tree 
    * @param value 
    */ 
public void insert(T value){ 
    if(isEmpty()) 
    root = new Node(value); //root node added 
    else 
    insert(root, value); //if not empty then insert based on root 
} 

/** 
    * Recursive method is called internally to insert nodes at proper 
    places depending on their vakues. 
    * @param node 
    * @param value 
    */ 
private void insert(Node node, T value){ 
    if(value.compareTo(node.value) < 0){ //if new value less than parent node 
    if(node.left == null) //if left null then add 
    node.left = new Node(value); 
    else 
    insert(node.left,value); //if left not null then recursive call 
    } 
    else if(value.compareTo(node.value) >= 0){ //if new value same or greater than parent node 
    if(node.right == null) //if right null then add 
    node.right = new Node(value); 
    else 
    insert(node.right,value); //if right not null then recursive call 
    } 
} 

訪問的完整源代碼的鏈接here