如果您不想在选择算法时使用 DFS 和 BFS 算法,则性能会更好。这是解决此类问题的简单方法。可能对你有帮助。
父子关系的模型类
class Relation {
String parent;
String child;
// constructor
public Relation(String parent, String child) {
super();
this.parent = parent;
this.child = child;
}
// setter getter toString methods
}
实际实施
public static Map<String, List<String>> getAllLevelOfChildren(List<Relation> relations){
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> tempList = null;
Set<String> parents = new HashSet<String>();
Set<String> children = new HashSet<String>();
for(Relation relation:relations){
parents.add(relation.getParent());
children.add(relation.getChild());
}
parents.removeAll(children);
for(String key:parents){
tempList = new ArrayList<String>();
map.put(key, tempList);
}
// Relation between Parent Child
for(Relation rel : relations){
if(parents.contains(rel.getParent())){
tempList = map.get(rel.getParent());
tempList.add(rel.getChild());
map.put(rel.getParent(), tempList);
}
for(String parent:parents){
tempList = map.get(parent);
if(tempList.contains(rel.getParent())){
tempList.add(rel.getChild());
map.put(parent, tempList);
}
}
}
// Relation between children
for (Relation rel : relations) {
for (String parent : parents) {
tempList = map.get(parent);
if (tempList.contains(rel.getParent()) && !tempList.contains(rel.getChild())) {
tempList.add(rel.getChild());
map.put(parent, tempList);
}
}
}
return map;
}
主要测试方法:
public static void main(String[] args) {
List<String> list = Arrays.asList("P1~C1","C1~C2","C2~C3","C3~C4","P2~C5","C5~C6","C6~C3");
System.out.println("Input List : "+list);
List<Relation> relations = list.stream().map(o->{
return new Relation(o.split("~")[0],o.split("~")[1]);
}).collect(Collectors.toList());
System.out.println("All level of Children : "+getAllLevelOfChildren(relations));
}
输出
Input List : [P1~C1, C1~C2, C2~C3, C3~C4, P2~C5, C5~C6, C6~C3]
All level of Children : {P1=[C1, C2, C3, C4], P2=[C5, C6, C3, C4]}