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
|
188 Discussions
|
Please Login in order to post a comment
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.
Further information. The data comes from "Test Case 1". Here is the graph assuming that u->v is a parent->child edge. But, several have to be swapped for this problem (left as an exercise for the reader). The first image (input1.png) shows the graph before swapping, and it shows multiple roots. Most of the graph is not reachable starting at node 1 (each node shows the node number and the value). The second image (input_oneTree.png) shows the graph you need to build for the HR test to be successful.
https://github.com/johnnyski/tc1/blob/main/input1.png https://github.com/johnnyski/tc1/blob/main/input1_oneTree.png
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.