在Java中向BST添加对象

时间:2012-12-05 00:29:24

标签: java binary-search-tree

我需要一些二叉搜索树的帮助。我清楚地知道如何将整数添加到二叉搜索树中,但是如何将整个对象添加到二进制搜索树中呢? http://postimage.org/image/6y0hor0gh/

假设我想使用AGE作为键值,那么在创建节点时如何比较对象?为了将二进制搜索树中的整数添加到

//Tree.java

public class Tree 
{   
    // The root node of the tree
    // initialised here to null
    private TreeNode root; 

    private TreeNode insert(TreeNode tree, int d)
    {
        if(tree == null) return new TreeNode(d);
        else if   (d < tree.data) tree.left  = insert(tree.left, d);
           else if(d > tree.data) tree.right = insert(tree.right,d);
       // ignore duplicate items
       return tree;
    } // end private TreeNode insert(TreeNode tree, int d)

    public void insert(int d)
    {   root = insert(root,d);  }


---------------------------------------------
//TreeNode.java

class TreeNode 
{
    protected TreeNode left;   // left node
    protected int data;        // data item
    protected TreeNode right;  // right node

   // Constructor
   TreeNode(int d) 
    {
        data = d; left = right = null;
    }
} // end of class TreeNode 

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:1)

看一下树图。你想要做的是让你的对象可比较并调用compareTo方法或为你的对象创建一个Comparator并使用它来对你的树进行排序。

所以而不是

else if   (d < tree.data) tree.left  = insert(tree.left, d);
       else if(d > tree.data) tree.right = insert(tree.right,d);

你会有

else if (d.compareTo(tree.data) < 0 ){
    tree.left  = insert(tree.left, d);
} else if (d.compareTo(tree.data) > 0){
    tree.right = insert(tree.right,d);
}
// what happens when they are the same ????