Java怎么实现树形List与扁平List互转

avatar
作者
筋斗云
阅读量:2

一种实现树形List与扁平List互转的方法是使用递归遍历树形结构。

首先,定义一个树节点的类,包含节点的值和子节点列表:

class TreeNode {     private int value;     private List<TreeNode> children;      // 构造函数      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;     }      // 添加子节点的方法      public void addChild(TreeNode child) {         this.children.add(child);     } } 

接下来,实现树形List转换为扁平List的方法:

public class TreeListConverter {     // 树形List转扁平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;     } } 

然后,实现扁平List转换为树形List的方法:

public class TreeListConverter {     // 扁平List转树形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;     } } 

注意,为了实现扁平List转换为树形List,需要在树节点类中添加一个父节点的引用。

使用示例:

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);     } } 

输出结果:

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!