67,512
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
List<Root> roots = new ArrayList<>();
roots.add(new Root(1, "根节点", 0));
roots.add(new Root(2, "一级节点", 1));
roots.add(new Root(3, "一级节点", 1));
roots.add(new Root(4, "二级节点", 2));
roots.add(new Root(5, "二级节点", 2));
roots.add(new Root(6, "三级节点", 5));
Integer rootId = findRootId(5, roots);
System.out.println(rootId);
}
private static Integer findRootId(Integer parentId, List<Root> roots) {
Integer rootId = null;
for (Root root : roots) {
if (root.getId().compareTo(parentId) == 0) {
if (root.getParentId().compareTo(0) != 0) {
rootId = findRootId(root.getParentId(), roots);
} else {
rootId = root.getId();
}
}
}
return rootId;
}
}
class Root {
private Integer id;
private String name;
private Integer parentId;
public Root(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
}