仅供参考,望采纳:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Main {
static class Node {
String name;
List<Node> children = new ArrayList<>();
}
static Map<String, Node> nodes = new HashMap<>();
static void buildTree(String source, String target) {
Node sourceNode = nodes.get(source);
if (sourceNode == null) {
sourceNode = new Node();
sourceNode.name = source;
nodes.put(source, sourceNode);
}
Node targetNode = nodes.get(target);
if (targetNode == null) {
targetNode = new Node();
targetNode.name = target;
nodes.put(target, targetNode);
}
sourceNode.children.add(targetNode);
}
static void getPaths(Node root, String path, List<String> paths) {
path += root.name + "-";
if (root.children.isEmpty()) {
paths.add(path.substring(0, path.length() - 1));
return;
}
for (Node child : root.children) {
getPaths(child, path, paths);
}
}
public static void main(String[] args) {
// 根据JSON数据中的关系构建树
List<Map<String, String>> relations = getRelationsFromJson();
for (Map<String, String> relation : relations) {
buildTree(relation.get("source"), relation.get("target"));
}
// 获取根节点(A)
Node root = nodes.get("A");
// 获取从根开始的所有路径
List<String> paths = new ArrayList<>();
getPaths(root, "", paths);
System.out.println(paths);
}
}