2014-07-19 65 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