Binary search tree generic - java

I have the following classes and I want to let the user choose whether he wants to create a BST with integers or a BST with strings. How can i create a BST from integers when the user choose 5 or create a BST from strings when the user press 6? Also if anyone find something wrong with my generics pls let me know!
Thanks a lot
public class BSTNode <T extends Comparable<T>>
{
T value;
BSTNode<T> left;
BSTNode<T> right;
public BSTNode(T value, BSTNode<T> l,BSTNode<T> r)
{
this.value = value;
left = l;
right = r;
}
public BSTNode(T value)
{
this(value,null,null);
}
public T getValue()
{
return value;
}
public void setValue(T value)
{
this.value = value;
}
public BSTNode<T> getLeftChild()
{
return left;
}
public BSTNode<T> getRightChild()
{
return right;
}
public void setLeftChild(BSTNode<T> node)
{
left = node;
}
public void setRightChild(BSTNode<T> node)
{
right = node;
}
public boolean search(T value)
{
if (value.equals(this.value))
return true;
else if (value.compareTo(this.value) < 0)
{
if (left == null)
return false;
else
return left.search(value);
} else if (value.compareTo(this.value) > 0)
{
if (right == null)
return false;
else
return right.search(value);
}
return false;
}
public boolean add(T value)
{
if (value.compareTo(this.value)==0)
return false;
else if (value.compareTo(this.value) < 0)
{
if (left == null)
{
left = new BSTNode<T>(value);
return true;
} else
return left.add(value);
}
else if (value.compareTo(this.value) > 0)
{
if (right == null)
{
right = new BSTNode<T>(value);
return true;
}
else
return right.add(value);
}
return false;
}
public boolean remove(T value2, BSTNode<T> parent)
{
if (value2.compareTo(this.value)<0)
{
if (left != null)
return left.remove(value2, this);
else
return false;
}
else if (value2.compareTo(this.value)>0)
{
if (right != null)
return right.remove(value2, this);
else
return false;
}
else
{
if (left != null && right != null)
{
this.value = right.minValue();
right.remove(this.value, this);
}
else if (parent.left == this)
{
parent.left = (left != null) ? left : right;
}
else if (parent.right == this)
{
parent.right = (left != null) ? left : right;
}
return true;
}
}
public T minValue()
{
if (left == null)
return value;
else
return left.minValue();
}
}
public class BinarySearchTree <T extends Comparable<T>>
{
private BSTNode<T> root;
public BinarySearchTree(T value)
{
root = new BSTNode<T>(value);
}
public BSTNode getRoot()
{
return root;
}
public boolean search(T value)
{
if (root.equals(null))
return false;
else
return root.search(value);
}
public boolean add(T value)
{
if (root == null) {
root = new BSTNode(value);
return true;
} else
return root.add(value);
}
public boolean remove(T value) {
if (root == null)
return false;
else {
if (root.getValue() == value) {
BSTNode auxRoot = new BSTNode(null);
auxRoot.setLeftChild(root);
boolean result = root.remove(value, auxRoot);
root = auxRoot.getLeftChild();
return result;
} else {
return root.remove(value, null);
}
}
}
public static void displayInorder(BSTNode T)
{
if (T!=null)
{
if (T.getLeftChild()!=null)
{
displayInorder(T.getLeftChild());
}
System.out.print(T.getValue() + " ");
if(T.getRightChild()!=null)
{
displayInorder(T.getRightChild());
}
}
}
}
import java.util.Scanner;
public class main {
public static void main(String[] args) {
BinarySearchTree b = new BinarySearchTree(null);
boolean flag = true;
while (flag) {
Scanner scan = new Scanner(System.in);
System.out.println("Select 1 to add values in to BST\n"
+ "Select 2 to delete values from the BST \n"
+ "Select 3 to search for a value\n"
+ "Select 4 to display te values held in the BST\n"
+ "Select 5 to create a BST of strings\n"
+ "Select 6 to create a BST of integers\n"
+ "Select 7 to exit" );
int opt = scan.nextInt();
switch (opt) {
case 1: System.out.println("Insert the value of your choice: ");
String str = scan.next();
b.add(str);
break;
case 2: System.out.println("Insert the value of your choice: ");
str = scan.next();
b.remove( str);
break;
case 3:
System.out.println("Insert the value of your choice: ");
str = scan.next();
b.search(str);
break;
case 4:
BinarySearchTree.displayInorder(b.getRoot());
break;
case 5:
case 7:
flag=false;
break;
}
}
}
}

In order to get the most of generics in your code this is my suggestions:
I would add a method to process a string (the user input) into the appropriate type in the tree class:
...
import java.util.function.Function;
...
public class BinarySearchTree <T extends Comparable<T>>
{
private BSTNode<T> root;
private Function<String,T> valueDecoder
public BinarySearchTree(final Function<String,T> valueDecoder)
{
this.valueDecoder = valueDecoder;
root = new BSTNode<T>(null);
}
...
public boolean decodeAndAdd(final String encodedValue) {
return add(valueDecoder.apply(encodedValue));
}
public boolean decodeAndRemove(final String encodedValue) {
return remove(valueDecoder.apply(encodedValue));
}
}
```
Then you would leave the b variable undefined/null until you actually now the type of tree given the choice provided by the user. Since it might contain String or Integer here you can only use ? as the type parameter, perhaps ? extends Comparable<?> as that is part of the constraint... ? is fine in this case:
BinarySearchTree<?> b = null;
Now when the user ask for a String or Integer tree you need to provide the appropriate lambda to transfer the scanned string into the actual element value:
case 5:
b = new BinarySearchTree<>(scanStr -> scanStr);
break;
case 6:
b = new BinarySearchTree<>(scanStr -> Integer.parseInt(scanStr));
break;
Now add and remove are trivial:
case 1:
b.decodeAndAdd(scan.next());
break;
case 2:
b.decodeAndRemove(scan.next());
break;
If the user provides a non-valid integer string value when the tree is an Integer tree it would result in a NumberFormatException and the program would stop. Perhaps you would rather show an error message and allow the user to do another operator. For that:
case 6:
b = new BinarySearchTree<>(scanStr -> {
try {
return Integer.parseInt(scanStr);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("you must provide a valid integer value: '" + scanStr + "'");
}
});
break;
...
case 1:
try {
b.decodeAndAdd(scan.next());
} catch (final IllegalArgumentException ex) {
System.err.println("ERROR: " + ex.getMessage());
}
break;
case 2:
try {
b.decodeAndRemove(scan.next());
} catch (final IllegalArgumentException ex) {
System.err.println("ERROR: " + ex.getMessage());
}
break;
Perhaps is not ideal to add decodeAndAdd and decodeAndRemove to your BinarySearchTree class if you want to keep things a bit more modular as the BST might be used outside the user command line context described in the question.
In that case you could define a generic "struct" like class that contains a reference that contains a reference to the BST and the decoding lambda with their element type bound to be the same using a type-parameter. You could also extends the BST class in another user-interface specialized BST that add this functionality:
class CommandLineBST<T> {
public final BST<T> tree;
public final Function<String, T> valueDecoder;
public CommandLineBST(final BST<T> tree, final Function<String, T> decoder) {
this.tree = tree;
this.valueDecoder = decoder;
}
public boolean add(final String scanStr) {
return tree.add(valueDecoder.apply(scanStr));
}
public boolean remove(final String scanStr) {
return tree.remove(valueDecoder.apply(scanStr));
}
}
or
class CommandLineBST<T> extends BST<T> {
private Function<String, T> valueDecoder;
public CommandLineBST(final Function<String, T> valueDecoder) {
super(null);
this.valueDecoder = valueDecoder;
}
public boolean decodeAndAdd(final String scanStr) { ... }
public boolean decodeAndRemove(final String scanStr) { ... }
}

Related

Binary search tree Searching troubleshooting

I've spent about two days pouring over this and I have no idea what's missing. Originally my BST used comparables, then I switched it to int to simplify it when it wasn't working.
I add several items to a tree and it successfully prints them out in order. Then, the first time I call the search() method it returns true, as it should. Every other search call after that returns false whether it is true or false.
I'm including most of my code here in case the problem isn't related with the search method itself.
The output SHOULD be: 4 12 23 27 30 42 60 84 true true false true true
but instead I get: 4 12 23 27 30 42 60 84 true false false false false
public class BSTree {
TreeNode root;
static int comparison;
public void insert(int value) {
if (root == null) {
root = new TreeNode(value);
}
else {
root.insert(value);
}
}
public boolean search(int chicken) {
if (root != null ) {
return root.search(chicken);
}
return false;
}
public static int height(TreeNode b) {
return TreeNode.height(b);
}
public static void CompareSet() {
comparison++;
}
public int getCompare() {
return comparison;
}
public void ResetCompare() {
comparison = 0;
}
public static void traverseInOrder (TreeNode node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(" " + node.data);
traverseInOrder (node.right);
}
}
public static void main(String args[]) {
BSTree tree = new BSTree();
tree.insert(30);
tree.insert(42);
tree.insert(84);
tree.insert(12);
tree.insert(4);
tree.insert(23);
tree.insert(27);
tree.insert(60);
traverseInOrder(tree.root);
System.out.println("\n" + tree.search(30));
System.out.println("\n" + tree.search(4));
System.out.println("" + tree.search(50));
System.out.println("" + tree.search(27));
System.out.println("" + tree.search(42));
System.out.println(height(tree.root));
}
}
Here is the treeNode class:
public class TreeNode<T> {
int data;
TreeNode left;
TreeNode right;
TreeNode(int value){
this.data = value;
//right = null;
//left = null;
}
public void insert(int value) {
if (value == data) {
return;
}
if (value < data) {
if (left == null) {
left = new TreeNode(value);
}
else {
left.insert(value);
}
}
else {
if (right == null) {
right = new TreeNode(value);
}
else {
right.insert(value);
}
}
public boolean search(int value) {
BSTree.CompareSet();
if (data == value) return true;
if (data < value && left!=null)
return left.search(value);
else if(data > value && right != null)
return right.search(value);
return false;
}
public static int height(TreeNode b) {
if (b == null) return -1;
return 1 + Math.max(height(b.left), height(b.right));
}
public int getData(){
return data;
}
public TreeNode getLeftChild() {
return left;
}
public void setLeftChild(TreeNode leftChild) {
this.left = leftChild;
}
public TreeNode getRightChild() {
return right;
}
public void setRightChild(TreeNode rightChild) {
this.right = rightChild;
}
}
Your comparaisons are reversed :))) Here is the corrected TreeNode::search method :
public boolean search(int value) {
BSTree.CompareSet();
if (data == value) return true;
if (data > value && left!=null)
return left.search(value);
else if(data < value && right != null)
return right.search(value);
return false;
}
I think you swapped the data and the value variables.
just change your search method of TreeNode class to this:
public boolean search(int value) {
Test.CompareSet();
if (data == value) return true;
if (data < value && right!=null)
return right.search(value);
else if(data > value && left != null)
return left.search(value);
return false;
}
When your current node's data is greater than value you need to go to left sub-tree. And when current node's data is smaller than value you need to go to right sub-tree. You just have done the reverse one.

binary tree of strings in java

I'm trying to create a binary tree of strings with constructors and methods of searching for an element and printing a binary tree. In main I want to check if the string is in a binary tree. Can someone help me? Thank you in advance
Here is an implementation of binary search tree with strings :
public static void main(String[] args) throws IOException {
boolean toExit = false;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BinaryTreeNode binaryTreeNode = new BinaryTreeNode("hello", "hello");
binaryTreeNode.put("world","world");
binaryTreeNode.put("ab","ab");
binaryTreeNode.put("cd","cd");
while(!toExit) {
System.out.println("Please enter string to search in the binary search tree or -1 to exit: ");
String input = bufferedReader.readLine();
if("-1".equals(input)){
toExit = true;
} else {
if (binaryTreeNode.get(input) == null) {
System.out.println("The input string does not exist");
} else {
System.out.println(input + " exists");
}
}
}
}
public static class BinaryTreeNode
{
private String key;
private Object value;
private BinaryTreeNode left, right;
public BinaryTreeNode(String key, Object value)
{
this.key = key;
this.value = value;
}
public Object get( String key )
{
if (this.key.equals(key))
{
return value;
}
if (key.compareTo(this.key) < 0 )
{
return left == null ? null : left.get(key);
}
else
{
return right == null ? null : right.get(key);
}
}
public void put(String key, Object value)
{
if (key.compareTo(this.key) < 0)
{
if (left != null)
{
left.put(key, value);
}
else
{
left = new BinaryTreeNode(key, value);
}
}
else if (key.compareTo(this.key) > 0)
{
if (right != null)
{
right.put(key, value);
}
else
{
right = new BinaryTreeNode(key, value);
}
}
else
{
this.value = value;
}
}
}
Hope that it helps...

Error java.lang.Integer is not within bounds of type-variable T; BinarySearchTree

I want to create a simple Binary Search Tree which uses generics to specify the data type.
However, when I want to create a new tree of Integers, I get the following error:
type argument java.lang.Integer is not within bounds of type-variable T
I tried other data types which are clearly extending Comparable, so why is this not working?
Here is my code:
Interface:
public interface Comparable<T>
{
int compareTo( T t );
}
BinarySearchTree:
public class BinarySearchTree<T extends Comparable<T>>
{
private T content;
private BinarySearchTree<T> leftChild, rightChild;
public BinarySearchTree()
{
content = null;
leftChild = null;
rightChild = null;
}
public T getContent()
{
if(!isEmpty())
{
return content;
}
else
{
throw new RuntimeException();
}
}
public boolean isEmpty()
{
return content == null;
}
public boolean isLeaf()
{
return !isEmpty() && leftChild.isEmpty() && rightChild.isEmpty();
}
public void add(T t)
{
if(isEmpty())
{
content = t;
leftChild = new BinarySearchTree<T>();
rightChild = new BinarySearchTree<T>();
}
else
{
if(content.compareTo(t) > 0)
{
leftChild.add(t);
}
if(content.compareTo(t) < 0)
{
rightChild.add(t);
}
}
}
public int size()
{
if(isEmpty())
{
return 0;
}
else
{
return 1 + leftChild.size() + rightChild.size();
}
}
public boolean contains(T t)
{
if(isEmpty())
{
return false;
}
else
{
if(content.compareTo(t) > 0)
leftChild.contains(t);
else if(content.compareTo(t) < 0)
rightChild.contains(t);
return true;
}
}
public void show()
{
if(!isEmpty())
{
leftChild.show();
System.out.println(content);
rightChild.show();
}
}
}
Main:
public class main
{
public static void main(String[] args)
{
test();
}
public static void test()
{
BinarySearchTree<Integer> tree = new BinarySearchTree<>();
tree.add("5");
tree.add("10");
tree.add("3");
tree.add("1");
tree.show();
}
}
The error comes with this line: BinarySearchTree<Integer> tree = new BinarySearchTree<>();
This is happening because you've defined your own interface Comparable<T>, of which Integer is not a subtype.
Delete your Comparable, and use the one in java.lang instead.
Also, as Eran pointed out, you shouldn't be adding String values to a BinarySearchTree<Integer>.
You should not create your own Comparable interface. It's a part JDK, you can use it.

Comparator doesn't work with Binary Tree

I have this thing
Comparator.java
public interface Comparator<T> {
public int compareTo(int num);
}
valueComparator.java
public class valueComparator implements Comparator<Tree.Node> {
#Override
public int compareTo(Tree.Node obj, int number) {
if (obj.getDataNumber() == number) {
return 0;
}
else if (obj.getDataNumber() < number) {
return -1;
}
else return 1;
}
}
Tree.java
public class Tree {
public Node root;
Tree() {
}
public static class Node {
Node(int number, String str, boolean flag) {
dataNumber = number;
dataText = str;
dataBool = flag;
}
public int getDataNumber() {
return this.dataNumber;
}
public String getDataText() {
return this.dataText;
}
public boolean getDataBool() {
return this.dataBool;
}
public void setDataText(String text) {
this.dataText = text;
}
public void isDataBool(boolean flag) {
this.dataBool = flag;
}
Node left;
Node right;
private int dataNumber;
private String dataText;
private boolean dataBool;
}
public void binaryTree() {
root = null;
}
public boolean search(int number) {
return search(root, number);
}
valueComparator comp = new valueComparator();
private boolean search(Node node, int number) {
if (node == null) {
return false;
}
if (comp.compareTo(node, number) == 0) {
return true;
}
if (comp.compareTo(node, number) == -1) {
return search(node.left, number);
}
else {
return search(node.right, number);
}
}
public void insertLeaf(int number, String str, boolean flag) {
root = insertLeaf(root, number, str, flag);
}
private Node insertLeaf(Node node, int number, String str, boolean flag) {
if (node == null) {
node = new Node(number, str, flag);
} else {
if (number < node.dataNumber) {
node.left = insertLeaf(node.left, number, str, flag);
}
else if (number > node.dataNumber) {
node.right = insertLeaf(node.right, number, str, flag);
}
else {
System.out.println("The element is already in the tree.");
}
}
return node;
}
}
Test.java
public class Test {
public static void main(String args[]) {
Tree binTree = new Tree();
binTree.binaryTree();
binTree.insertLeaf(5, "text2", true);
binTree.insertLeaf(4, "text4", false);
binTree.insertLeaf(1, "text1", true);
binTree.insertLeaf(3, "text3", true);
binTree.insertLeaf(2, "text5", false);
System.out.println("Element 3 found: " + binTree.search(3));
// Element 3 found: false
}
}
I am supposed to do the search with a comparator, but I fail to understand the logic. The compareTo method works for itself but it stucks at the recursive call of search. After the first pass, if the return of compareTo is not = 0, then it enters with null and breaks out of recursion and returns false. Meaning if I set the first element of the tree to be '3', the search(3) will return true, but if it's different than 3 - false and won't even look for it in the tree.
When you insert a number you compare it directly to the nodes' values and if the number is less than the value stored in the current node, you follow the left pointer.
However when you search for a number, you use a comparator, which compares the node's value to the number given (note the opposite order!) and if the number is less than the value in the current node, you follow a right link.
Use either direct comparision or a comparator, as you wish – but use the same method everywhere.

Inserting right children on left side of BST, and vice versa

I'm having a little bit of difficulty with my insert method for this homework assignment. I have most of it done, but for some reason whenever my program is supposed to insert a node as a right child on the left side of the tree it just inserts it as a left child.
I kind of do my comparison in a weird way (signs should be reversed for a lot of them, but it worked like that for some reason) so please bear with me if you have difficulty in reading it.
I know that this is a horrible way to implement a binary search tree, and I would never ever do it in the real world, but it's homework and thus -- I have no choice.
Any and all help is appreciated, as always. Thank you!
Edit: I know where the problem is now. It's within the searchFor() method. Instead of the node's rightful parent, it makes the parent the root of the tree (in this case the parent of the node is always "cup".)
now that that's out of the way, can anyone offer up a solution?
Edit2: Took some of the extra stuff out that I don't think is relevant to the problem. I'm pretty sure I've narrowed it down to the searchFor() method. Whenever I call to return the parent of the current node, it will return the root of the tree ("cup.") I think that's why I'm having my problems, since it inserts based on that.
Thanks for all the help so far, I really appreciate it.
public class BinarySearchTree //implements Comparator
{
private Comparator<Object> dataComparator;
private LinkedListWithTwoLinks tree;
public static void main (String[] args)
{
BinarySearchTree bst;
Object hold;
String[] words = {"cup", "shaker", "cord", "key", "addressbook", "date", "address", "cupcake",
"card", "tape", "page", "day", "key", "days", "dayt"};
bst = new BinarySearchTree(new AlphabeticComparator());
System.out.println("[1]: original tree");
for(int i=0; i<words.length; i++) if (!bst.insert(words[i])) { System.out.println(">>>>>>>>>>>>> " + words[i] + " is already in tree"); }
bst.inOrder();
}
public static class AlphabeticComparator implements Comparator <Object>
{
public int compare(Object x, Object y)
{
if ( x == y ) return 0;
if ( x == null) return -1;
if ( y == null) return 1;
return (x.toString().compareTo(y.toString()));
}
}
public static class LastCharacterComparator implements Comparator <Object>
{
public int compare(Object x, Object y)
{
String xs;
String ys;
if ( x == y ) return 0;
if ( x == null ) return -1;
if ( y == null) return 1;
xs = x.toString();
ys = y.toString();
if ( xs.length() == 0) return -1;
if ( ys.length() == 0) return 1;
return (xs.charAt(xs.length()-1) - ys.charAt(ys.length()-1));
}
}
public BinarySearchTree(Comparator<Object> y)
{
dataComparator = y;
this.tree = new LinkedListWithTwoLinks();
}
private int compare(BinarySearchTreeElementInterface s, Object data)
{
return this.dataComparator.compare(s, data);
}
public boolean insert(Object data)
{
boolean success;
BinarySearchTreeElementInterface current;
BinarySearchTreeElementInterface parent;
current = getRoot();
parent = null;
success = false;
if (current == null)
{
getTree().insert(data);
return true;
}
else
{
SearchResult insert;
insert = searchFor(data);
//if (data == "shaker") {System.out.println(insert.resultOfCompare); }
while (current != null)
{
if (insert.insertAsLeftChild())
{
//if (data == "card") {System.out.println("IN RIGHT");}
//System.out.println("IN LEFT");
parent = current;
current = current.getLeftChild();
}
else if (insert.insertAsRightChild())
{
//if (data == "card") {System.out.println("IN RIGHT");}
parent = current;
current = current.getRightChild();
}
}
if (insert.insertAsLeftChild())
{
//parent.setLeftChild(insert.getParentOfLocation()); //insert.getParentOfLocation()
//System.out.println(data);
getTree().insertUsingPrior(parent, data);
//System.out.println(insert.getParentOfLocation()+" bye left");
// System.out.println(insert.getLocation()+" hi");
success = true;
}
else if (insert.insertAsRightChild())
{
//parent.setRightChild(insert.getParentOfLocation());
//System.out.println(data);
getTree().insertUsingNext(parent, data);
//System.out.println(insert.getParentOfLocation()+" bye right");
// System.out.println(insert.getLocation());
success = true;
}
else {success = false;}
/*
figures out if it should be inserted as a left or right child
then call insert using prior/next
}*/
}
return success;
}
private SearchResult searchFor(Object data)
{
/*returns either to node containing the data or the parent of the node of which the data would be a child of*/
if (getTree() == null) {throw new ListEmptyException("Tree is empty!");}
BinarySearchTreeElementInterface currentLocation;
BinarySearchTreeElementInterface parent;
SearchResult destination;
parent = getRoot();
currentLocation = parent;
while (currentLocation != null)
{
if (currentLocation.getData() == data)
{
return new SearchResult(parent, currentLocation, compare(currentLocation, data));
}
if (compare(currentLocation, data) < 0)
{
//System.out.println("IN LEFT");
parent = currentLocation;
currentLocation = currentLocation.getLeftChild();
}
else if (compare(currentLocation, data) > 0)
{
//System.out.println("IN RIGHT");
parent = currentLocation;
currentLocation = currentLocation.getRightChild();
}
}
destination = new SearchResult(parent, currentLocation, compare(parent, data));
//System.out.println(destination.resultOfCompare);
return destination;
/*
* use nothing but BSTEIs
*/
}
public void inOrder()
{
inOrder(getRoot());
}
public void inOrder(BinarySearchTreeElementInterface BSTroot)
{
//System.out.println(BSTroot.getRightChild());
if (BSTroot != null)
{
inOrder(BSTroot.getLeftChild());
System.out.println(BSTroot.getData());
inOrder(BSTroot.getRightChild());
}
/*if (BSTroot.getLeftChild() != null)
{
}
System.out.println(BSTroot.getData());
if (BSTroot.getRightChild() != null)
{
inOrder(BSTroot.getRightChild());
//System.out.println(BSTroot.getData());
}
System.out.println(BSTroot.getData());*/
}
public int size()
{
return tree.size();
}
/*SEARCH RESULT CLASS-----------------------------------------------------------------------------------------*/
public class SearchResult
{
BinarySearchTreeElementInterface location;
BinarySearchTreeElementInterface parentOfLocation;
int resultOfCompare;
public SearchResult(BinarySearchTreeElementInterface parent, BinarySearchTreeElementInterface locate, int comp)
{
this.parentOfLocation = parent;
this.location = locate;
this.resultOfCompare = comp;
}
public BinarySearchTreeElementInterface getLocation()
{
return this.location;
}
public BinarySearchTreeElementInterface getParentOfLocation()
{
return this.parentOfLocation;
}
public boolean insertAsLeftChild()
{
if (resultOfCompare > 0) {return true;}
else {return false;}
}
public boolean insertAsRightChild()
{
if (resultOfCompare < 0) {return true;}
else {return false;}
}
public boolean locationIsLeftOfParent()
{
return this.location == parentOfLocation.getLeftChild();
}
public boolean locationisRightOfParent()
{
return this.location == parentOfLocation.getRightChild();
}
public boolean wasSearchSuccessful()
{
return this.parentOfLocation == this.location;
}
public void setLocation(BinarySearchTreeElementInterface newLocation)
{
this.location = newLocation;
}
public void setLocationOfParent(BinarySearchTreeElementInterface newParentLocation)
{
this.parentOfLocation = newParentLocation;
}
}
}
compare(x, y) method of BinarySearchTree is wrong.
It compares a node to a data with a comparator made to compare data against data. Change 'Object' to 'String' and it will not compile while your sample data are strings.
This should fix it:
private int compare(BinarySearchTreeElementInterface s, Object data)
{
return this.dataComparator.compare(s.getData(), data);
}
In your SearchResult class, do you have the way it determines a left or right insert swapped?
public boolean insertAsLeftChild()
{
if (resultOfCompare > 0) {return true;}
else {return false;}
}
If the compare is greater than 0, it should be interested as a right child, correct?

Categories

Resources