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
|
186 Discussions
|
Please Login in order to post a comment
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.
The problem description is tricky and easily misleading. Specifically it says:
...Each of the subsequent lines contains two space-separated integers,
*ui*
and*vi*
, describing an edge between nodes*u*
and*v*
.An edge input like this:
3 4
does not mean that
3
is the parent. The parent may as well be noted on the right side. The correct interpretation:There is just a link between 3 and 4, it's unspecified which one is tree node/leaf node.
Can anyone tell me what do we have to do in this module
This code works fine for me
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Iterator;
enum Color { RED, GREEN }
abstract class Tree { private int value; private Color color; private int depth;
}
class TreeNode extends Tree { private ArrayList 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 sumInLeaves = 0;
}
class ProductOfRedNodesVisitor extends TreeVis { private long productOfRedNodes = 1L; private static final int MOD = 1000000007;
}
class FancyVisitor extends TreeVis { private int sumOfValuesNonLeafEvenDepth = 0; private int sumOfValuesGreenLeaf = 0;
}
public class Solution { static Map tree = new HashMap<>();
}