JAVA实现list<string>转换成多叉树结构代码
时间: 2023-12-08 17:06:09 浏览: 77
以下是JAVA实现list<string>转换成多叉树结构的代码示例:
```
import java.util.ArrayList;
import java.util.List;
public class TreeNode {
private String value;
private List<TreeNode> children;
public TreeNode(String value) {
this.value = value;
this.children = new ArrayList<>();
}
public String getValue() {
return value;
}
public List<TreeNode> getChildren() {
return children;
}
public void addChild(TreeNode child) {
this.children.add(child);
}
public static TreeNode buildTree(List<String> list) {
TreeNode root = new TreeNode("");
for (String s : list) {
TreeNode current = root;
String[] values = s.split(",");
for (String value : values) {
current = addChildIfNotExist(current, value);
}
}
return root.getChildren().get(0);
}
private static TreeNode addChildIfNotExist(TreeNode parent, String value) {
for (TreeNode child : parent.getChildren()) {
if (child.getValue().equals(value)) {
return child;
}
}
TreeNode newChild = new TreeNode(value);
parent.addChild(newChild);
return newChild;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A,B,C,D");
list.add("A,B,C,E,F");
list.add("A,G,H,I");
TreeNode root = TreeNode.buildTree(list);
printTree(root, 0);
}
private static void printTree(TreeNode node, int depth) {
System.out.println(getIndent(depth) + node.getValue());
for (TreeNode child : node.getChildren()) {
printTree(child, depth + 1);
}
}
private static String getIndent(int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append("\t");
}
return sb.toString();
}
}
```
使用示例:
```
List<String> list = new ArrayList<>();
list.add("A,B,C,D");
list.add("A,B,C,E,F");
list.add("A,G,H,I");
TreeNode root = TreeNode.buildTree(list);
printTree(root, 0);
```
输出结果:
```
A
B
C
D
E
F
G
H
I
```
阅读全文