java - Searching in a unsorted tree recursively -


i'm trying search element e in tree, can see search(position,e) doesn't return position. when add "return null;" @ end of method. works when position i'm looking @ left children of parent , returns null otherwise. how can keep working until reaches end of tree?

public position<e> search(e e) {     return search(root(), e); }  public position<e> search(position<e> p, e e) {     if(p.getelement().equals(e))         return p;     for(position<e> c: children(p))             return search(c, e); } 

i think issue in loop:

for(position<e> c: children(p))         return search(c, e); 

imagine element you're searching in second child of node rather first. above code, on first iteration of loop, you'll recursively explore first child, returns false, return false without having had chance explore second child. in other words, method looks @ first child, might not find you're looking for.

to fix this, try rewriting code this:

if(p.getelement().equals(e))     return p;  for(position<e> c: children(p)) {     position<e> result = search(c, e);     if (result != null) return result; } return null; 

this makes recursive call in each subtree. if 1 call fails find element, that's fine - continue next. if 1 call find element, return it. if none of calls find element, return null indicate failure.

hope helps!


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -