user1848495
user1848495

Reputation:

Adding objects to BST in Java

I need some help with binary search trees. I clearly know how to add integers to binary search tree, but how can I add the whole object to a binary search tree like there? http://postimage.org/image/6y0hor0gh/

Let's say that I want to use AGE a key value, so how can I compare object to object when creating nodes? For adding integers to binary search tree I used

//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 

Any ideas? Thanks

Upvotes: 1

Views: 2604

Answers (1)

BevynQ
BevynQ

Reputation: 8259

have a look at tree map. What you want to do is either make your object comparable and call the compareTo method or create a Comparator for your object and use that to sort your tree.

so instead of

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

you would have

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 ????

Upvotes: 2

Related Questions