We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classSumInLeavesVisitorextendsTreeVis{privateintsum=0;publicintgetResult(){returnsum;}publicvoidvisitNode(TreeNodenode){// No action needed for internal nodes in this visitor}publicvoidvisitLeaf(TreeLeafleaf){sum+=leaf.getValue();}}classProductOfRedNodesVisitorextendsTreeVis{privatedoubleproduct=1;publicintgetResult(){return(int)product;}publicvoidvisitNode(TreeNodenode){increaseProduct(node);}publicvoidvisitLeaf(TreeLeafleaf){increaseProduct(leaf);}privatevoidincreaseProduct(Treetree){if(tree.getColor()==Color.RED){product=(product*tree.getValue())%(Math.pow(10,9)+7);}}}classFancyVisitorextendsTreeVis{privateintnonLeafNodeSum=0;privateintgreenLeafSum=0;publicintgetResult(){returnMath.abs(nonLeafNodeSum-greenLeafSum);}publicvoidvisitNode(TreeNodenode){if(node.getDepth()%2==0){nonLeafNodeSum+=node.getValue();}}publicvoidvisitLeaf(TreeLeafleaf){if(leaf.getColor()==Color.GREEN){greenLeafSum+=leaf.getValue();}}}publicclassSolution{publicstaticTreesolve(){Scannerscan=newScanner(System.in);intn=Integer.parseInt(scan.nextLine());StringvaluesLine=scan.nextLine();StringcolorsLine=scan.nextLine();String[]valuesStr=valuesLine.split(" ");int[]values=newint[n];for(inti=0;i<n;i++){values[i]=Integer.parseInt(valuesStr[i]);}String[]colorsStr=colorsLine.split(" ");byte[]colors=newbyte[n];for(inti=0;i<n;i++){colors[i]=(byte)Integer.parseInt(colorsStr[i]);}Map<Integer,List<Integer>>adj=newHashMap<>();boolean[]visited=newboolean[n];for(inti=0;i<n;i++){adj.put(i,newArrayList<Integer>());}while(scan.hasNextInt()){intu=scan.nextInt()-1;intv=scan.nextInt()-1;adj.get(u).add(v);adj.get(v).add(u);}scan.close();returnbuildTree(0,0,values,colors,adj,visited);}publicstaticTreebuildTree(intindex,intdepth,int[]values,byte[]colors,Map<Integer,List<Integer>>adj,boolean[]visited){booleanisLeaf=true;visited[index]=true;Colorcolor=colors[index]==0?Color.RED:Color.GREEN;List<Integer>children=adj.get(index);TreeNodetreeNode=newTreeNode(values[index],color,depth);for(intchild:children){if(!visited[child]){isLeaf=false;TreechildNode=buildTree(child,depth+1,values,colors,adj,visited);treeNode.addChild(childNode);}}if(isLeaf){returnnewTreeLeaf(values[index],color,depth);}else{returntreeNode;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Visitor Pattern
You are viewing a single comment's thread. Return to all comments →