카테고리 없음

chat gpt java list to tree

nayha 2024. 1. 15. 13:15

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TreeNode {
   int value;
   List<TreeNode> children;

   public TreeNode(int value) {
       this.value = value;
       this.children = new ArrayList<>();
   }
}

public class ListToTreeConverter {

   public static void main(String[] args) {
       List<Map<String, Object>> flatList = createFlatList();
       TreeNode root = convertListToTree(flatList);
       // 이제 'root'를 사용하여 트리를 조작하거나 출력할 수 있습니다.
   }

   private static TreeNode convertListToTree(List<Map<String, Object>> flatList) {
       Map<Integer, TreeNode> nodeMap = new HashMap<>();

       for (Map<String, Object> item : flatList) {
           int parentId = (int) item.get("parentId");
           int nodeId = (int) item.get("id");

           TreeNode currentNode = nodeMap.computeIfAbsent(nodeId, TreeNode::new);

           if (parentId != 0) {
               TreeNode parentNode = nodeMap.computeIfAbsent(parentId, TreeNode::new);
               parentNode.children.add(currentNode);
           }
       }

       return nodeMap.get(1);  // 1은 루트 노드의 ID라고 가정합니다.
   }

   private static List<Map<String, Object>> createFlatList() {
       // 예시로 사용할 평면 리스트 생성
       List<Map<String, Object>> flatList = new ArrayList<>();

       Map<String, Object> node1 = new HashMap<>();
       node1.put("id", 1);
       node1.put("parentId", 0);

       Map<String, Object> node2 = new HashMap<>();
       node2.put("id", 2);
       node2.put("parentId", 1);

       Map<String, Object> node3 = new HashMap<>();
       node3.put("id", 3);
       node3.put("parentId", 1);

       Map<String, Object> node4 = new HashMap<>();
       node4.put("id", 4);
       node4.put("parentId", 2);

       flatList.add(node1);
       flatList.add(node2);
       flatList.add(node3);
       flatList.add(node4);

       return flatList;
   }
}

반응형