Java 递归模板

public static List<Node> buildTree(List<Node> nodes) {
    Map<Integer, List<Node>> map = new HashMap<>();
    for (Node node : nodes) {
        if (!map.containsKey(node.getPid())) {
            map.put(node.getPid(), new ArrayList<>());
        }
        map.get(node.getPid()).add(node);
    }
    return buildTree(map, 0);
}

private static List<Node> buildTree(Map<Integer, List<Node>> map, int parentId) {
    List<Node> tree = new ArrayList<>();
    if (map.containsKey(parentId)) {
        for (Node node : map.get(parentId)) {
            node.setChildren(buildTree(map, node.getId()));
            tree.add(node);
        }
    }
    return tree;
}
 

在该递归函数中,我们首先创建一个Map,用于将父节点ID映射到其子节点。然后,我们传递给buildTree方法一个Map和一个父ID,它将返回一个节点列表,该列表包含具有父ID的所有子节点。如果一个节点没有子节点,则其子节点列表为空。

要将ID,PID格式与此递归函数一起使用,您只需将Node类定义为具有ID和PID字段的类,并将其节点对象添加到节点列表中,如下所示:

public class Node {
    private int id;
    private int pid;
    private String name;
    private List<Node> children;

    // 构造函数、getter、setter等方法略

    public static void main(String[] args) {
        List<Node> nodes = new ArrayList<>();
        nodes.add(new Node(1, 0, "root"));
        nodes.add(new Node(2, 1, "child1"));
        nodes.add(new Node(3, 1, "child2"));
        nodes.add(new Node(4, 2, "grandchild1"));
        nodes.add(new Node(5, 2, "grandchild2"));
        nodes.add(new Node(6, 3, "grandchild3"));

        List<Node> tree = buildTree(nodes);
        // 对树进行操作或打印
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值