# Binary Search Tree Lookup Method

• May 15th, 2012, 03:56 AM
Sbonett
Binary Search Tree Lookup Method
Hi guys, I'm having a bit of trouble creating the search method for the BST. I've come up with the following:

Code :

``` public AnyClass search(String key) {   BNode currentNode = root;   while (true) { int cmp = newNode.compareTo(currentNode);   if (cmp < 0) { BNode nextNode = currentNode.getLeft(); if (nextNode == null) { currentNode.getLeft(); return null; } currentNode = nextNode; } else if (cmp > 0) { BNode nextNode = currentNode.getRight(); if (nextNode == null) { currentNode.getRight(); return null; } currentNode = nextNode; } else if (cmp == 0) { return cmp; } } }```

BNode

Code :

```package binarynodes;   import dataobjects.AnyClass;   public class BNode { public BNode left, right; public AnyClass obj;   public BNode(AnyClass newObj){ left = null; right = null; obj = newObj; }   public void setLeft(BNode left){ this.left = left; }   public void setRight(BNode right){ this.right = right; }   public BNode getLeft(){return left;} public BNode getRight(){return right;}   public void setKey(AnyClass newObj){this.obj = newObj;} public AnyClass getKey(){return obj;}   public void print(){   System.out.println(obj.getData()); }   public int compareTo(BNode other) { return obj.compareTo(other.obj); }   }```

I need to create a getKey method to BNode so that I can get the key of the currentNode so than I can compare string against string. How do I go about doing this?

Thanks
• May 15th, 2012, 07:43 AM
copeg
Re: Binary Search Tree Lookup Method
Quote:

I need to create a getKey method to BNode so that I can get the key of the currentNode so than I can compare string against string. How do I go about doing this?
I'm not sure what you are asking...the BNode class you posted already has a getKey method.