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
|
189 Discussions
|
Please Login in order to post a comment
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 {
This is my take on this problem:
Nowhere in the problem it is stated that one of the two nodes of an edge is 100% the parent. Which means, you cannot assume it.
You can work yourself through construction level by level, with a queue. Dequeue the next potential parent, and enqueue all implemented children. Save all edges in an adjacent list, then implement this strategy.
Mark all visited nodes! You don't want to accidentally attatch a parent as another child.
Modulo needs clarification. You are expected to use it on every calculation for every node, and not on the final sum.
This is my solution:
For my solution, the problem statement requires some clarification.
I reviewed some comments, and find more efficient data structure to solve whever use recursive or non recursive way. Recursive:
Non recutsive:
I have to say that before you submit, you probably won't know that the edge is not pointing from the parent node to the descendant node, and you won't know that the order in which nodes appear is not top-down...
It seems that several exercises have encountered similar problems in my memory, which has lowered the impression of this website in my mind。
In the end, it took a lot of time to improve and perfect, and a non recursive tree building process was implemented.Only posted the process of building the tree, by the way, it uses Java8.