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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。