package main.java.recursive;

import java.util.*;

public class TreeStructure {

    public static void main(String[] args) {
        List<TreeNode> treeNodes = new ArrayList<>();
        Set<Integer> leafSet = new HashSet<>();
        treeNodes.add(new TreeNode(1,0,"root"));
        treeNodes.add(new TreeNode(2,1,"a1"));
        treeNodes.add(new TreeNode(3,1,"a2"));
        treeNodes.add(new TreeNode(4,2,"b1"));
        treeNodes.add(new TreeNode(5,4,"c1"));

        Map<Integer, TreeNode> treeMap = new HashMap<>();

        for (TreeNode treeNode : treeNodes) {
            leafSet.add(treeNode.getId());
        }

        for (TreeNode treeNode : treeNodes) {
            treeMap.put(treeNode.getId(), treeNode);
            leafSet.remove(treeNode.getParentId());
        }

        for (Integer id: leafSet) {
            int parentId = treeMap.get(id).getParentId();
            int nodeId = id;
            while (parentId != 0) {
                treeMap.get(parentId).addChild(treeMap.get(nodeId));
                nodeId = parentId;
                parentId = treeMap.get(nodeId).getParentId();
            }
        }

        TreeNode finalNode = treeMap.values().stream()
                .filter(treeNode -> treeNode.getParentId() == 0).toList().getFirst();

        System.out.println(finalNode);
    }
}
