Tree Constructor Coderbyte Solution

0

Have the function TreeConstructor(strArr) take the array of strings stored in strArr, which will contain pairs of integers in the following format: (i1,i2), where i1 represents a child node in a tree and the second integer i2 signifies that it is the parent of i1. For example: if strArr is ["(1,2)", "(2,4)", "(7,2)"], then this forms the  tree   


                                         

which you can see forms a proper binary tree. Your program should, in this case, return the string true because a valid binary tree can be formed. If a proper binary tree cannot be formed with the integer pairs, then return the string false. All of the integers within the tree will be unique, which means there can only be one node in the tree with the given integer value.

Examples 1


 Input: new String[] {"(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"}
 Output: true


Examples 2


 Input: new String[] {"(1,2)", "(3,2)", "(2,12)", "(5,2)"}
 Output: false


Tree Constructor Coderbyte Solution 


  import java.util.*;
 import java.io.*;

 class Main {

 public static String TreeConstructor(String[] strArr) {
   Set<String> children = new HashSet<>();
   Map<String, Integer> parents = new HashMap<>();
      for(String node: strArr){
       String[] values = node.replaceAll("[^0-9,]", "").split(",");
       children.add(values[0]);
       Integer parentsCount = parents.get(values[1]);
       if(parentsCount != null parentsCount + 1 > 2) {
           return "false";
       }else {
        parents.put(values[1], (parentsCount == null ? 1 : ++parentsCount));
       }
   }
   return "" + (children.size()==strArr.length);
 }

 public static void main (String[] args) {

   Scanner s = new Scanner(System.in);
   System.out.print(TreeConstructor(s.nextLine()));
 }

 }



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !