6、假设树的上下级之间是通过id和pid进行关联,pid为null代表是顶层节点,用java编写一个方法,将平铺结构的json数组转换成层级结构。(20分) 例:输入[ {"id" : 1, "pid": nul, "value":1}, {"id" : 1, "pid":2, "value":2},"id" :3,"pid": null, "value": 3}] 输出: ("d'"1,"pid": nll, "lue":1, cilenea'r'" :1, "ld".2, vaue".2, hrern("id" :3, "pid": nul, "alue": 3, cildre:[]}]
时间: 2023-07-02 21:22:36 浏览: 283
以下是一个递归实现的示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> item1 = new HashMap<>();
item1.put("id", 1);
item1.put("pid", null);
item1.put("value", 1);
data.add(item1);
Map<String, Object> item2 = new HashMap<>();
item2.put("id", 2);
item2.put("pid", 1);
item2.put("value", 2);
data.add(item2);
Map<String, Object> item3 = new HashMap<>();
item3.put("id", 3);
item3.put("pid", 1);
item3.put("value", 3);
data.add(item3);
Map<String, Object> item4 = new HashMap<>();
item4.put("id", 4);
item4.put("pid", 2);
item4.put("value", 4);
data.add(item4);
Map<String, Object> item5 = new HashMap<>();
item5.put("id", 5);
item5.put("pid", 2);
item5.put("value", 5);
data.add(item5);
Map<String, Object> item6 = new HashMap<>();
item6.put("id", 6);
item6.put("pid", 3);
item6.put("value", 6);
data.add(item6);
Map<String, Object> item7 = new HashMap<>();
item7.put("id", 7);
item7.put("pid", 3);
item7.put("value", 7);
data.add(item7);
List<Map<String, Object>> tree = buildTree(data, null);
System.out.println(tree);
}
public static List<Map<String, Object>> buildTree(List<Map<String, Object>> data, Object pid) {
List<Map<String, Object>> tree = new ArrayList<>();
for (Map<String, Object> item : data) {
if (pid == item.get("pid")) {
List<Map<String, Object>> children = buildTree(data, item.get("id"));
if (!children.isEmpty()) {
item.put("children", children);
}
tree.add(item);
}
}
return tree;
}
}
```
其中,`buildTree` 方法的参数 `data` 是平铺结构的 JSON 数组,`pid` 初始值为 `null`,表示从顶层节点开始构建树。在方法中,我们遍历 `data` 数组,找到 `pid` 为当前节点的子节点,并递归调用 `buildTree` 方法来构建子树。如果当前节点有子节点,我们将它们存储在 `children` 属性中,最后返回当前层级的树结构。最外层的 `tree` 列表即为完整的树形结构。
阅读全文