gpt4 book ai didi

java - 创建家谱树java

转载 作者:搜寻专家 更新时间:2023-11-01 03:02:32 25 4
gpt4 key购买 nike

我有以下结构:

Member {
String firstName;
String secondName;
Member[] children;
Member father;
}
  • 我必须用 java 实现这棵树;
  • 我有一个成员的名字和第二个名字。我需要找到从根节点到那个节点的路径。有谁可以帮助我吗?

这是我的:

公共(public)类成员{

public List<Member> children = new ArrayList<>();
public Member father = null;
public String secondName = null;
public String firstName = null;

public Member(String secondName, String firstName) {
this.secondName = secondName;
this.firstName = firstName;
}

public Member(String secondName, String firstName, Member father) {
this.secondName = secondName;
this.firstName = firstName;
this.father = father;
}

public List<Member> getChildren() {
return children;
}

public void setFather(Member father) {
this.father = father;
father.addChild(this);

}

public void addChild(String secondName, String firstName) {
Member child = new Member(secondName, firstName);
child.setFather(this);
this.children.add(child);
}

public void addChild(Member child) {
child.setFather(this);
this.children.add(child);
}

public String getSecondName() {
return this.secondName;
}

public String getFirstName() {
return this.firstName;
}

public void setSecondName(String secondName) {
this.secondName = secondName;
}

public void setPrenume(String firstName) {
this.firstName = firstName;
}

public boolean isRoot() {
return (this.father == null);
}

public void deleteFather() {
this.father = null;
}

最佳答案

您的结构类似于我在申请中使用的 ona。我通过创建通用 walker 解决了这个问题,它从根部向下遍历三个,并使用访问者模式为我提供遍历结果。

如果你把它转换成你的问题,它看起来像这样:

public class SimpleWalker<T>{

private Visitor<T> visitor;


public SimpleWalker(Visitor<T> visitor) {
this.visitor= visitor;
}

public void walk(Member node) {


if (visitor.visit(node)) {
for (Member child : node.children) {
walk(child);
}
}
visitor.leave(node);

}

public T getResult() {
return visitor.getResult();
}

}

然后是访客界面

public interface Visitor<T> {
boolean visit(Member node);
void leave(Member node);
T getResult();
}

实现看起来像那样

public class Pathfinder implements Visitor<List<Member>> {
final private String firstname, secondname;//passed by constructor
boolean found = false;
List<Member> path = new ArrayList<>();

public boolean visit(Member node) {
if (node.firstname.equals(firstname)
&& node.secondname.equals(secondname)) {
found = true;
return false;
}
return true;
}

public void leave(Member node) {
if (found){
path.add(0, node);
}
}

public List<Member> getResult() {
return path;
}
}

这个解决方案的优点是,无论您想在树中做什么,例如查找元素、计算某人的后代数量,您都可以使用 walker,您需要做的就是创建新访问者。

关于java - 创建家谱树java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120186/

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