java - whats wrong with my method for searching a non-binary tree (n-ary tree)? -


hi have code search n-ary tree dosent works correctly , dont know whats wrong when searching n4 , n5 return n3 whats wrong? enter image description here

public familynode findnodebyname(familynode nodename ){ if(this.name.equals(nodename.name)){ // found node named nodename, return return this; } // that's not me looking for, let's see kids for(familynode child : this.children){ if(child.findnodebyname(nodename) != null) return child; // found looking, return here // return child; } // finished looping on nodes , did not find any, return null return null; } 

the reason because give node in node found. once node found, node needs returned, , parent nodes in case familynode found needs return found familynode. check done found variable.

you need this:

familynode found = child.findnodebyname(nodename); if(found != null) return found; 

the entire method like:

public familynode findnodebyname(familynode nodename ){ if(this.name.equals(nodename.name)){ return this; } for(familynode child : this.children){ familynode found = child.findnodebyname(nodename); if(found != null) return found; } return null; } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -