Link to home
Start Free TrialLog in
Avatar of dalydude
dalydude

asked on

polymorphic binary search tree using singleton design pattern

I'm implementing a polymorphic binary search tree and I'm having a problem with my insert method. The code only inserts items into the right side of the tree. I have to implement the method recursively without a helper method.
public NonEmptyTree<K, V> insert(K key, V value) {
int result = key.compareTo(this.key);
		if (result == 0) {
			--size;
			this.val= value;
			return this;
		}
		if (result > 0) { 
			right = right.insert(key, value);  
		} else if (result < 0) {
			left = left.insert(key, value);
		}
		return this;

Open in new window

Avatar of imladris
imladris
Flag of Canada image

That method looks fine. Certainly, it appears to clearly distinguish between a result of 0, less than 0 and greater than zero, and the corresponding insertion here, on the right or the left.

So, if your tree is always inserting on the right, my guess would be that the flaw lies in the compareTo method always returning a result greater than 0.....
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial