Saturday, 15 January 2011

java - Implementing a Binary Search Tree - Contains method -



java - Implementing a Binary Search Tree - Contains method -

i have 3 classes - dictionaryapp, bstset , bstnode - both bstset , bstnode have contains methods.

public class bstset <e extends comparable<e>> extends abstractset <e> { // root of supporting binary search tree private bstnode<e> root; // number of elements in set private int count = 0; public boolean isempty() { homecoming count == 0; } public boolean contains(e item) throws classcastexception { if(root == null) homecoming false; homecoming root.contains(item); } public boolean add(e item) { if (item == null) throw new illegalargumentexception("null cannot added bstset"); if(contains(item))return false; if(root == null){ root = new bstnode(item); count++; homecoming true; }else{ root.add(item); count++; homecoming true; } } } public class bstnode <e extends comparable<e>> { private e value; private bstnode<e> left; public bstnode<e> right; public bstnode(e value) { this.value = value; } public e getvalue() { homecoming value; } public bstnode<e> getleft() { homecoming left; } public bstnode<e> getright() { homecoming right; } public boolean contains(e item) { if(item.compareto(value) == 0) homecoming true; if(left != null) left.contains(item); if(right != null) right.contains(item); // no matching node found homecoming false; } public boolean add(e item) { if(item.compareto(value) < 0) {left = new bstnode(item); homecoming true;} if(item.compareto(value) > 0) {right = new bstnode(item); homecoming true;} homecoming false; } }

my issues contains method in bstnode class never returns true , can't understand why. if see anymore of code or need anymore info please sense free ask.

in bstnode's contains method, ignoring results of calling contains on left , right. if kid node found it, homecoming true immediately. also, utilize result of comparing determine kid search next.

public boolean contains(e item) { int comp = item.compareto(value); if(comp == 0) homecoming true; if(comp < 0 && left != null && left.contains(item)) homecoming true; if(comp > 0 && right != null && right.contains(item)) homecoming true; // no matching node found homecoming false; }

your add method ignores kid nodes may exist. test presence first. if don't exist, assign doing. if exist, phone call add recursively on child.

public boolean add(e item) { if(item.compareto(value) < 0) { if (left == null) left = new bstnode(item); homecoming true; else homecoming left.add(item); } if(item.compareto(value) > 0) { if (right == null) right = new bstnode(item); homecoming true; else homecoming right.add(item); } homecoming false; }

java binary-search-tree

No comments:

Post a Comment