用Java把树形数据转成列表,再把列表转成树形数据 From NewBing

用Java把树形数据转成列表,再把列表转成树形数据 From NewBing_第1张图片

public static List<TreeNode> treeToList(List<TreeNode> tree) {
    List<TreeNode> list = new ArrayList<>();
    for (TreeNode node : tree) {
        list.add(node);
        if (node.getChildren() != null) {
            list.addAll(treeToList(node.getChildren()));
        }
    }
    return list;
}

用Java把树形数据转成列表,再把列表转成树形数据 From NewBing_第2张图片

public static List<TreeNode> listToTree(List<TreeNode> list) {
    List<TreeNode> tree = new ArrayList<>();
    for (TreeNode node : list) {
        if (node.getParentId() == null) {
            tree.add(findChildren(node, list));
        }
    }
    return tree;
}

private static TreeNode findChildren(TreeNode node, List<TreeNode> list) {
    for (TreeNode child : list) {
        if (node.getId().equals(child.getParentId())) {
            if (node.getChildren() == null) {
                node.setChildren(new ArrayList<>());
            }
            node.getChildren().add(findChildren(child, list));
        }
    }
    return node;
}

你可能感兴趣的:(Java,数据结构,New,Bing,java,数据结构)