import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TreeBuilder {
static class TreeNode {
private int id;
private int parentId;
private String name;
private List<TreeNode> children = new ArrayList<>();
public TreeNode(int id, int parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public int getId() {
return id;
}
public int getParentId() {
return parentId;
}
public String getName() {
return name;
}
public List<TreeNode> getChildren() {
return children;
}
public void addChild(TreeNode child) {
this.children.add(child);
}
@Override
public String toString() {
return "TreeNode{" +
"id=" + id +
", name='" + name + '\'' +
", children=" + children +
'}';
}
}
public static List<TreeNode> buildTree(List<TreeNode> nodes) {
Map<Integer, TreeNode> nodeMap = nodes.stream()
.collect(Collectors.toMap(TreeNode::getId, node -> node));
List<TreeNode> rootNodes = new ArrayList<>();
for (TreeNode node : nodes) {
if (node.getParentId() == 0) {
rootNodes.add(node);
} else {
TreeNode parent = nodeMap.get(node.getParentId());
if (parent != null) {
parent.addChild(node);
}
}
}
return rootNodes;
}
public static void main(String[] args) {
List<TreeNode> nodeList = new ArrayList<>();
nodeList.add(new TreeNode(1, 0, "Root1"));
nodeList.add(new TreeNode(2, 0, "Root2"));
nodeList.add(new TreeNode(3, 1, "Child1.1"));
nodeList.add(new TreeNode(4, 1, "Child1.2"));
nodeList.add(new TreeNode(5, 3, "Child1.1.1"));
nodeList.add(new TreeNode(6, 2, "Child2.1"));
List<TreeNode> tree = buildTree(nodeList);
System.out.println(tree);
}
}