Moh*_*iri 5 java arrays tree search
我写了这个n-array树类现在我想编写一个方法来将一个子节点添加到我树中的特定节点,方法是:首先我应该搜索我的树找到父亲,然后将子节点添加到该节点.我不知道如何申报我的方法
public class FamilyNode {
public String name;
public String Family;
public String sex;
public FamilyNode Father;
public FamilyNode Mother;
public FamilyNode Spouse=null;
public String status="alive";
public int population;
public ArrayList<FamilyNode> children=new ArrayList<FamilyNode>() ;
public FamilyNode(String firstname,String lastname,String sex1){
this.name=firstname;
this.Family=lastname;
this.sex=sex1;
this.population=this.children.size()+1;
}
public void SetParents(FamilyNode father,FamilyNode mother){
this.Father=father;
this.Mother=mother;
}
public void SetHW(FamilyNode HW){
this.Spouse=HW;
}
public int Number (){
int number_of_descendants = this.population;
if(this.Spouse!=null) number_of_descendants++;
for(int index = 0; index < this.children.size(); index++)
number_of_descendants = number_of_descendants+ this.children.get(index).Number();
return number_of_descendants;
}
public void AddChild(FamilyNode Father,FamilyNode child){
//the code here
}
}
Run Code Online (Sandbox Code Playgroud)
我昨天回答了您的相关问题之一,所以让我们继续我发布的代码:)
public class FamilyNode {
// ...
// ...
public FamilyNode findNodeByName(String nodeName){
if(name.equals(nodeName)){
// 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 : children){
if(child.findNodeByName(nodeName) != null)
// 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;
}
public void addChild(FamilyNode child){
children.add(child);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,您需要找到您正在寻找的节点(在本例中是按名称),这可以通过findNodeByName上面的方法来完成。找到该节点后,向其添加一个子节点。
像这样使用此代码:
FamilyNode root = ...;
FamilyNode node = root.findNodeByName("Parent");
if(node != null) node.addChild(...);
Run Code Online (Sandbox Code Playgroud)
注意 如果您想调试并访问所有树节点,请使用此方法:
public FamilyNode findNodeByName(String nodeName){
System.out.println("Visiting node "+ name);
// That's not me that you are looking for, let's see my kids
for(FamilyNode child : children){
child.findNodeByName(nodeName)
}
// Finished looping over all nodes and did not find any, return null
return null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4867 次 |
| 最近记录: |