i have project working on involves making database of movies. have movie object , problem having trouble printing out movies have same title. 1 of movies being printed out. sure search function in binarysearchtree
class working because finds correctly, think stopping once search condition met , doesn't other possible movies same title. think solve need implement loop
print out each movie as found when traversing binarysearchtree.
here search function in binarysearchtree
:
public node search( movie m ){ if ( root == null ){ system.out.println("no items search."); return null; }else{ return search( m, root ); } } private node search( movie m, node n){ if ( m.compareto( n.getdata() ) == 0 ){ if(n.getleft() != null){//go left continue searching node node = search(m, n.getleft()); if(node != null) return node; } return n; }else{ if ( n.getright() == null ){ system.out.println("item not found."); return null; }else{ return search(m, n.getright()); } } }
the implementation in main prints out 1 of movies same title (the first 1 comes across). need loop think or way keep iterating through tree.
public static binarysearchtree findbytitle( binarysearchtree tree ){ scanner input = new scanner(system.in); system.out.println("enter title of movie: "); movie temp = new movie( input.nextline() ); node leftmost = tree.search(temp); if( leftmost != null ){ while(leftmost != null && temp.compareto( leftmost.getdata() ) == 0){ system.out.println(leftmost.getdata()); leftmost = leftmost.getright(); } } return tree; }
first, can left entry modifying search function:
private node search( movie m, node n){ if ( m.compareto( n.getdata() ) == 0 ){ if(n.getleft() != null){//go left continue searching node node = search(m, n.getleft()); if(node != null) return node; } return n; } if ( m.compareto( n.getdata() ) < 0 ){ if( n.getleft() == null){ system.out.println("item not found."); return null; }else{ return search(m, n.getleft()); } }else{ if ( n.getright() == null ){ system.out.println("item not found."); return null; }else{ return search(m, n.getright()); } }
after getting left node, keep getting right until movie's title not equals.
node leftmost = search(m); if(leftmost != null){ while(leftmost != null && m.compareto(leftmost.getdata()) == 0){ system.out.println(leftmost.getdata()); leftmost = leftmost.getright(); } }
Comments
Post a Comment