Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank of Programming Language Java . At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.
In this post, you will find the solution for Java Visitor Pattern -HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.
Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.
Introduction To Java
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++.
Link for the Problem – Java Visitor Pattern – Hacker Rank Solution
Java Visitor Pattern – Hacker Rank Solution
Note: In this problem you must NOT generate any output on your own. Any such solution will be considered as being against the rules and its author will be disqualified. The output of your solution must be generated by the uneditable code provided for you in the solution template.
An important concept in Object-Oriented Programming is the open/closed principle, which means writing code that is open to extension but closed to modification. In other words, new functionality should be added by writing an extension for the existing code rather than modifying it and potentially breaking other code that uses it. This challenge simulates a real-life problem where the open/closed principle can and should be applied.
A Tree class implementing a rooted tree is provided in the editor. It has the following publicly available methods:
getValue()
: Returns the value stored in the node.getColor()
: Returns the color of the node.getDepth()
: Returns the depth of the node. Recall that the depth of a node is the number of edges between the node and the tree’s root, so the tree’s root has depth and each descendant node’s depth is equal to the depth of its parent node .
In this challenge, we treat the internal implementation of the tree as being closed to modification, so we cannot directly modify it; however, as with real-world situations, the implementation is written in such a way that it allows external classes to extend and build upon its functionality. More specifically, it allows objects of the TreeVis class (a Visitor Design Pattern) to visit the tree and traverse the tree structure via the accept
method.
There are two parts to this challenge.
Part I: Implement Three Different Visitors
Each class has three methods you must write implementations for:
getResult()
: Return an integer denoting the , which is different for each class:- The SumInLeavesVisitor implementation must return the sum of the values in the tree’s leaves only.
- The ProductRedNodesVisitor implementation must return the product of values stored in all red nodes, including leaves, computed modulo . Note that the product of zero values is equal to .
- The FancyVisitor implementation must return the absolute difference between the sum of values stored in the tree’s non-leaf nodes at even depth and the sum of values stored in the tree’s green leaf nodes. Recall that zero is an even number.
visitNode(TreeNode node)
: Implement the logic responsible for visiting the tree’s non-leaf nodes such that the getResult method returns the correct for the implementing class’ visitor.visitLeaf(TreeLeaf leaf)
: Implement the logic responsible for visiting the tree’s leaf nodes such that the getResult method returns the correct for the implementing class’ visitor.
Part II: Read and Build the Tree
Read the -node tree, where each node is numbered from to . The tree is given as a list of node values (), a list of node colors (), and a list of edges. Construct this tree as an instance of the Tree class. The tree is always rooted at node number .
Your implementations of the three visitor classes will be tested on the tree you built from the given input.
Input Format
The first line contains a single integer, , denoting the number of nodes in the tree. The second line contains space-separated integers describing the respective values of .
The third line contains space-separated binary integers describing the respective values of . Each denotes the color of the node, where denotes red and denotes green.
Each of the subsequent lines contains two space-separated integers, and , describing an edge between nodes and .
Constraints
- It is guaranteed that the tree is rooted at node .
Output Format
Do not print anything to stdout, as this is handled by locked stub code in the editor. The three getResult()
methods provided for you must return an integer denoting the for that class’ visitor (defined above). Note that the value returned by ProductRedNodesVisitor‘s getResult method must be computed modulo .
Sample Input
5 4 7 2 5 12 0 1 0 0 1 1 2 1 3 3 4 3 5
Sample Output
24 40 15
Explanation

Locked stub code in the editor tests your three class implementations as follows:
- Creates a SumInLeavesVisitor object whose getResult method returns the sum of the leaves in the tree, which is . The locked stub code prints the returned value on a new line.
- Creates a ProductOfRedNodesVisitor object whose getResult method returns the product of the red nodes, which is . The locked stub code prints the returned value on a new line.
- Creates a FancyVisitor object whose getResult method returns the absolute difference between the sum of the values of non-leaf nodes at even depth and the sum of the values of green leaf nodes, which is . The locked stub code prints the returned value on a new line.
Java Visitor Pattern – Hacker Rank Solution
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; enum Color { RED, GREEN } abstract class Tree { private int value; private Color color; private int depth; public Tree(int value, Color color, int depth) { this.value = value; this.color = color; this.depth = depth; } public int getValue() { return value; } public Color getColor() { return color; } public int getDepth() { return depth; } public abstract void accept(TreeVis visitor); } class TreeNode extends Tree { private ArrayList<Tree> children = new ArrayList<>(); public TreeNode(int value, Color color, int depth) { super(value, color, depth); } public void accept(TreeVis visitor) { visitor.visitNode(this); for (Tree child : children) { child.accept(visitor); } } public void addChild(Tree child) { children.add(child); } } class TreeLeaf extends Tree { public TreeLeaf(int value, Color color, int depth) { super(value, color, depth); } public void accept(TreeVis visitor) { visitor.visitLeaf(this); } } abstract class TreeVis { public abstract int getResult(); public abstract void visitNode(TreeNode node); public abstract void visitLeaf(TreeLeaf leaf); } /* ---------- */ class SumInLeavesVisitor extends TreeVis{ int result=0; public int getResult(){ return result; } public void visitNode(TreeNode node){ } public void visitLeaf(TreeLeaf leaf){ result+=leaf.getValue(); } } class ProductOfRedNodesVisitor extends TreeVis{ long result=1; final int M=1000000007; public int getResult(){ return (int)result; } public void visitNode(TreeNode node){ if(node.getColor()==Color.RED){ result=(result*node.getValue())%M; } } public void visitLeaf(TreeLeaf leaf){ if(leaf.getColor()==Color.RED){ result=(result * leaf.getValue())%M; } } } class FancyVisitor extends TreeVis{ int even=0; int green=0; public int getResult(){ return Math.abs(even-green); } public void visitNode(TreeNode node){ if(node.getDepth()%2==0){ even+=node.getValue(); } } public void visitLeaf(TreeLeaf leaf){ if(leaf.getColor()==Color.GREEN){ green+=leaf.getValue(); } } } class Solution{ static int values[]; static Color colors[]; static Map<Integer, Set<Integer>> nodesMap = new HashMap<>(); public static Tree solve(){ Scanner in=new Scanner(System.in); int nnodes=in.nextInt(); values= new int[nnodes]; for(int i=0;i<nnodes;i++)values[i]=in.nextInt(); colors = new Color[nnodes]; for(int i=0;i<nnodes;i++)colors[i]=(in.nextInt()==0)?Color.RED:Color.GREEN; Tree rootNode; if(nnodes==1){ rootNode=new TreeLeaf(values[0],colors[0],0); }else{ rootNode=new TreeNode(values[0],colors[0],0); for(int i=0;i<(nnodes-1);i++) { int u = in.nextInt(); int v = in.nextInt(); Set<Integer> uEdges = nodesMap.get(u); if(uEdges==null)uEdges = new HashSet<>(); uEdges.add(v); nodesMap.put(u, uEdges); Set<Integer> vEdges = nodesMap.get(v); if(vEdges==null)vEdges = new HashSet<>(); vEdges.add(u); nodesMap.put(v, vEdges); } for(int nodeid:nodesMap.get(1)){ nodesMap.get(nodeid).remove(1); createEdge(rootNode, nodeid); } } return rootNode; } private static void createEdge(Tree parent,int nodeid){ Set<Integer> nodeEdges = nodesMap.get(nodeid); boolean hasChild = nodeEdges!=null && !nodeEdges.isEmpty(); if(hasChild){ TreeNode node = new TreeNode(values[nodeid-1],colors[nodeid-1],parent.getDepth()+1); ((TreeNode)parent).addChild(node); for(int neighborid:nodeEdges){ nodesMap.get(neighborid).remove(nodeid); createEdge(node, neighborid); } }else{ TreeLeaf leaf = new TreeLeaf(values[nodeid-1],colors[nodeid-1],parent.getDepth()+1); ((TreeNode)parent).addChild(leaf); } } /* ---------- */ public static void main(String[] args) { Tree root = solve(); SumInLeavesVisitor vis1 = new SumInLeavesVisitor(); ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor(); FancyVisitor vis3 = new FancyVisitor(); root.accept(vis1); root.accept(vis2); root.accept(vis3); int res1 = vis1.getResult(); int res2 = vis2.getResult(); int res3 = vis3.getResult(); System.out.println(res1); System.out.println(res2); System.out.println(res3); } }
Hey! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?
A formidable share, I simply given this onto a colleague who was doing a little bit analysis on this. And he the truth is purchased me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you thoughts updating your weblog with more details? It’s highly useful for me. Big thumb up for this blog post!
Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.
I do accept as true with all the ideas you have introduced on your post. They’re very convincing and will definitely work. Nonetheless, the posts are very brief for starters. May you please extend them a bit from next time? Thank you for the post.
Your style is so unique compared to many other people. Thank you for publishing when you have the opportunity,Guess I will just make this bookmarked.2
My brother recommended I might like this website. He was entirely right. This post actually made my day. You cann’t imagine just how much time I had spent for this information! Thanks!
I’d always want to be update on new posts on this internet site, bookmarked! .
Appreciate it for helping out, excellent info .
I’m really enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Exceptional work!
Yeah bookmaking this wasn’t a risky conclusion great post! .
Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to everything. Do you have any suggestions for inexperienced blog writers? I’d definitely appreciate it.
I found your blog website on google and check just a few of your early posts. Continue to maintain up the excellent operate. I simply extra up your RSS feed to my MSN Information Reader. In search of ahead to reading more from you afterward!…
I am now not certain where you are getting your information, however great topic. I must spend a while learning much more or figuring out more. Thanks for magnificent info I was searching for this information for my mission.
I’ve recently started a website, the information you provide on this site has helped me greatly. Thank you for all of your time & work. “So full of artless jealousy is guilt, It spills itself in fearing to be spilt.” by William Shakespeare.
This internet site is my inhalation, really fantastic pattern and perfect articles.
I was recommended this blog by means of my cousin. I’m not positive whether or not this submit is written through him as nobody else know such distinct about my trouble. You’re wonderful! Thank you!
It is truly a great and useful piece of information. I’m satisfied that you shared this helpful info with us. Please stay us up to date like this. Thank you for sharing.
cheap cialis without prescription buy cialis online safely medicine erectile dysfunction
order cefadroxil 250mg pill order duricef for sale generic propecia
order fluconazole generic buy fluconazole 100mg for sale purchase cipro without prescription
estradiol 2mg cost buy estrace 2mg pills buy generic minipress over the counter
buy metronidazole 400mg without prescription flagyl sale generic cephalexin
mebendazole over the counter tadalafil over the counter purchase tadalis for sale
order generic cleocin 150mg erythromycin 250mg sale sildenafil generic
avana 200mg pill avanafil 200mg for sale diclofenac 100mg without prescription
tamoxifen 10mg cheap buy rhinocort generic buy ceftin paypal
bimatoprost allergy spray robaxin tablet trazodone 100mg usa
buy amoxicillin online cheap cheap arimidex 1mg biaxin over the counter
There are plenty of places online where you can play casino games for free. However, we truly believe that you’ll have the best experience playing at MrGamez since we focus on bringing high-quality games rather than a high quantity of games. We also focus on site speed, ease of use and to enable users to play without downloading or signing up for anything. Free Daily Spins is operated under licence by Small Screen Casinos Ltd, which is regulated by the UK Gambling Commission and the Alderney Gambling Commission. All communications are encrypted, making Free Daily Spins safe, secure and trusted. Small Screen Casinos Ltd is licensed and regulated in Great Britain by the Gambling Commission under account number 39397. Rewards are bonuses, standard minimum wagering requirement applies. Your funds are segregated and protected.
http://www.gbuav.co.kr/bbs/board.php?bo_table=free&wr_id=50421
If you want to claim the latest Mecca Bingo bonus codes, you’ve reached the right page! This Mecca Bingo review uncovers essential details about the platform, such as its available games, payment methods and support means. The Mecca Bingo coupon code is also sometimes called a promotion code or Mecca bonus code. All of these names mean the same, as they refer to a special code that gives you something extra. For the below, however, you do not need to input any code to claim the bonus. Mecca bingo its a best bingo site in the online bingo industry.Played here a few years ago from a 5 no deposit bonus cashed out 200,in two days the money was in… Taking all of this into consideration it is easy to see why Mecca Bingo is as great as the operator claims it is. This platform offers some excellent bingo games, courtesy of Playtech, one of the major developers of games of chance. Mecca Bingo also provides players with the opportunity to claim several worthwhile promotions to enhance the overall experience. When all is said and done, the only logical conclusion is that Mecca Bingo is an excellent bingo platform and you should seriously consider becoming a member.
buy sildenafil 100mg without prescription buy suhagra 50mg sale buy sildalis medication
buy catapres without a prescription oral clonidine 0.1mg buy spiriva 9mcg generic
minocycline oral actos 30mg brand order actos 30mg online cheap
absorica for sale online order zithromax 500mg pill azithromycin ca
viagra cialis order cialis 40mg generic order generic tadalafil 20mg
buy generic azithromycin over the counter buy prednisolone generic neurontin generic
ivermectin topical buy prednisone for sale deltasone 10mg brand
buy generic lasix over the counter doxycycline 100mg cheap albuterol brand
order levitra 10mg generic brand plaquenil plaquenil brand
ramipril 5mg ca buy generic etoricoxib order arcoxia 60mg generic
vardenafil 10mg without prescription purchase tizanidine generic buy hydroxychloroquine 200mg
mesalamine online buy asacol online buy irbesartan 150mg
buy benicar 10mg generic order olmesartan for sale divalproex pills
clobetasol usa cost temovate cheap cordarone 100mg
buy acetazolamide without prescription how to get imdur without a prescription imuran 50mg tablet
Good post however , I was wondering if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit more. Kudos!
buy digoxin 250mg without prescription buy molnupiravir purchase molnupiravir online
carvedilol canada cheap cenforce 50mg buy chloroquine pills
naproxen 500mg cost cefdinir sale buy lansoprazole pills for sale
I like the valuable information you provide for your articles. I will bookmark your weblog and test again here frequently. I am slightly certain I will learn many new stuff right right here! Good luck for the next!