一種實現樹形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]