Java怎么實(shí)現(xiàn)樹形List與扁平List互轉(zhuǎn)

小億
152
2024-01-23 15:36:43
欄目: 編程語言

一種實(shí)現(xiàn)樹形List與扁平List互轉(zhuǎn)的方法是使用遞歸遍歷樹形結(jié)構(gòu)。

首先,定義一個(gè)樹節(jié)點(diǎn)的類,包含節(jié)點(diǎn)的值和子節(jié)點(diǎn)列表:

class TreeNode {
    private int value;
    private List<TreeNode> children;

    // 構(gòu)造函數(shù)

    public TreeNode(int value) {
        this.value = value;
        this.children = new ArrayList<>();
    }

    // getter和setter方法

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }

    // 添加子節(jié)點(diǎn)的方法

    public void addChild(TreeNode child) {
        this.children.add(child);
    }
}

接下來,實(shí)現(xiàn)樹形List轉(zhuǎn)換為扁平List的方法:

public class TreeListConverter {
    // 樹形List轉(zhuǎn)扁平List
    public static List<TreeNode> flattenList(List<TreeNode> treeList) {
        List<TreeNode> flatList = new ArrayList<>();
        for (TreeNode node : treeList) {
            flatList.add(node);
            flatList.addAll(flattenList(node.getChildren()));
        }
        return flatList;
    }
}

然后,實(shí)現(xiàn)扁平List轉(zhuǎn)換為樹形List的方法:

public class TreeListConverter {
    // 扁平List轉(zhuǎn)樹形List
    public static List<TreeNode> buildTreeList(List<TreeNode> flatList) {
        Map<Integer, TreeNode> nodeMap = new HashMap<>();
        List<TreeNode> treeList = new ArrayList<>();
        for (TreeNode node : flatList) {
            nodeMap.put(node.getValue(), node);
            if (node.getParentId() == null) {
                treeList.add(node);
            } else {
                TreeNode parent = nodeMap.get(node.getParentId());
                parent.addChild(node);
            }
        }
        return treeList;
    }
}

注意,為了實(shí)現(xiàn)扁平List轉(zhuǎn)換為樹形List,需要在樹節(jié)點(diǎn)類中添加一個(gè)父節(jié)點(diǎn)的引用。

使用示例:

public class Main {
    public static void main(String[] args) {
        List<TreeNode> treeList = new ArrayList<>();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        node1.addChild(node2);
        node1.addChild(node3);
        node2.addChild(node4);
        node2.addChild(node5);
        node3.addChild(node6);
        treeList.add(node1);

        List<TreeNode> flatList = TreeListConverter.flattenList(treeList);
        System.out.println(flatList);

        List<TreeNode> treeList2 = TreeListConverter.buildTreeList(flatList);
        System.out.println(treeList2);
    }
}

輸出結(jié)果:

[1, 2, 4, 5, 3, 6]
[1]

0