嗨我有这个代码来搜索一个n-ary树,但它不能正常工作,我不知道这是什么错 当搜索n4和n5时,它返回n3 怎么了?
public FamilyNode findNodeByName(FamilyNode nodeName ){
if(this.name.equals(nodeName.name)){
// We found a node named nodeName, return it
return this;
}
// That's not me that you are looking for, let's see my kids
for(FamilyNode child : this.children){
if(child.findNodeByName(nodeName) != null)
return child;
// We found what we are looking, just return from here
// return child;
}
// Finished looping over all nodes and did not find any, return null
return null;
}
答案 0 :(得分:1)
原因是您返回找到节点的节点。找到节点后,需要返回此节点,如果找到FamilyNode
,则父节点需要返回找到的FamilyNode
。检查found
变量的作用。
你需要做这样的事情:
FamilyNode found = child.findNodeByName(nodeName);
if(found != null)
return found;
整个方法如下:
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;
}