gpt4 book ai didi

java - 如何将 child 添加到 n 数组树中的特定节点?

转载 作者:搜寻专家 更新时间:2023-10-31 20:29:56 26 4
gpt4 key购买 nike

我写了这个 n-array 树类。我想编写一个方法来将一个子节点添加到我的树中的特定节点。

首先,我应该搜索我的树以找到父亲,然后将 child 添加到该节点的 child 中。我不知道我应该如何声明我的方法

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
}
}

最佳答案

我回答了你的一个related questions昨天让我们继续我发布的代码:)

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);
}
}

基本上,您需要找到您正在寻找的节点(在本例中是通过名称),这可以通过上面的 findNodeByName 来完成。找到节点后,向其添加一个子节点。

像这样使用这段代码:

FamilyNode root = ...;
FamilyNode node = root.findNodeByName("Parent");
if(node != null) node.addChild(...);

注意如果你想调试和访问你所有的树节点,使用这个方法:

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;
}

关于java - 如何将 child 添加到 n 数组树中的特定节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com