Untitled

 avatar
unknown
plain_text
a month ago
1.4 kB
2
Indexable
  public TreeNode createTree(int[] parent) {
        // Create a map to hold the list of children for each parent
        Map<Integer, List<Integer>> childrenMap = new HashMap<>();

        int rootVal = -1;

        // Populate the children map and find the root
        for (int i = 0; i < parent.length; i++) {
            if (parent[i] == -1) {
                rootVal = i; // Identify the root
            } else {
                childrenMap.putIfAbsent(parent[i], new ArrayList<>());
                childrenMap.get(parent[i]).add(i); // Add the current node to its parent's children list
            }
        }

       
        return buildTree(rootVal, childrenMap);
    }

    private TreeNode buildTree(int nodeVal, Map<Integer, List<Integer>> childrenMap) {
        // Base case: if the node doesn't exist, return null
        if (nodeVal == -1) return null;

        // Create the current node
        TreeNode node = new TreeNode(nodeVal);

        // Get the list of children for this node
        List<Integer> children = childrenMap.getOrDefault(nodeVal, new ArrayList<>());

        // Assign left and right children recursively
        if (children.size() > 0) {
            node.left = buildTree(children.get(0), childrenMap);
        }
        if (children.size() > 1) {
            node.right = buildTree(children.get(1), childrenMap);
        }

        return node;
    }
Leave a Comment