Question: I need help getting this Java program to run. import java.util.*; public class DrawTree { public String[] draw(int[] parents, String[] names) { int rootIndex =

I need help getting this Java program to run.

import java.util.*;

public class DrawTree { public String[] draw(int[] parents, String[] names) { int rootIndex = findRoot(parents); List result = new ArrayList<>(); drawSubtree(parents, names, rootIndex, "", result); return result.toArray(new String[result.size()]); } private int findRoot(int[] parents) { for (int i = 0; i < parents.length; i++) { if (parents[i] == -1) { return i; } } return -1; // invalid input } private void drawSubtree(int[] parents, String[] names, int rootIndex, String prefix, List result) { result.add(prefix + "+-" + names[rootIndex]); List children = new ArrayList<>(); for (int i = 0; i < parents.length; i++) { if (parents[i] == rootIndex) { children.add(i); } } children.sort(Comparator.comparingInt(i -> i)); for (int child : children) { drawSubtree(parents, names, child, prefix + " |", result); } } }

//here is the class DrawTree drawTree = new DrawTree(); int[] parents = {-1, 0, 1, 1, 0, 0, 5, 5}; String[] names = {"Root", "SubB", "LEAF1", "LEAF2", "LEAF3", "SubA", "LEAF4", "LEAF5"}; String[] result = drawTree.draw(parents, names); for (String line : result) { System.out.println(line); }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!