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.
- Prepare
- Java
- Advanced
- Java Visitor Pattern
- Discussions
Java Visitor Pattern
Java Visitor Pattern
Sort by
recency
|
193 Discussions
|
Please Login in order to post a comment
java8 working f9- import java.util.*;
enum Color { RED, GREEN }
abstract class Tree { private int value; private Color color; private int depth;
}
class TreeNode extends Tree { private List children = new ArrayList<>();
}
class TreeLeaf extends Tree { public TreeLeaf(int value, Color color, int depth) { super(value, color, depth); }
}
abstract class TreeVis { public abstract int getResult(); public abstract void visitNode(TreeNode node); public abstract void visitLeaf(TreeLeaf leaf); }
class SumInLeavesVisitor extends TreeVis { private int sum = 0;
}
class ProductRedNodesVisitor extends TreeVis { private long product = 1; private final int MOD = 1000000007;
}
class FancyVisitor extends TreeVis { private int evenDepthNonLeafSum = 0; private int greenLeafSum = 0;
}
public class Solution { public static Tree solve() { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] values = new int[n]; byte[] colors = new byte[n];
}
This problem leads one to believe that the input data is a tree. But in fact, it is an undirected graph. The lack of this information made me waste a lot of time solving the problem.
Here is Java visitor pattern solution - https://programmingoneonone.com/hackerrank-java-visitor-pattern-problem-solution.html
class SumInLeavesVisitor extends TreeVis { public int getResult() { //implement this return leavesValuesCounter; }
// private private int leavesValuesCounter = 0; }
class ProductOfRedNodesVisitor extends TreeVis { public int getResult() { //implement this return productOfRedNodesCounter; }
}
class FancyVisitor extends TreeVis { public int getResult() { //implement this return Math.abs(sumGreenLeafNodes - sumNonLeafNodes); }
}
public class Solution {