faye3721 2023-01-01 11:38 采纳率: 50%
浏览 91
已结题

关于#java#的问题,如何解决?

各位,求一个java算法,根据json数据,返回树的所有路径
如下json返回 A-B-C-D和A-E
json如下:
{
"result":{

    "relations":[
        
        {
            "source":"A",
            "target":"B"
        },
        {
            "source":"B",
            "target":"C"
        },
        {
            "source":"C",
            "target":"D"
        },
        {
            "source":"A",
            "target":"E"
        }
    ]
},
"status":{
    "code":0,
    "desc":"success"
}

}

  • 写回答

6条回答 默认 最新

  • |__WhoAmI__| 2023-01-01 11:56
    关注

    仅供参考,望采纳:

    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);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 1月11日
  • 已采纳回答 1月3日
  • 创建了问题 1月1日

悬赏问题

  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 STM32阿里云平台显示不了传感器采集的数据