Q. Write code to traverse a tree and return the sum of the values (Node.getValue()) of all nodes at the level N in the tree?
|
1 2 3 4 5 6 7 8 |
package tree; import java.util.List; public interface Node<E> { E getValue(); List<Node<E>> getChildren(); } |
A. Let’s have a basic implementation of the above Node interface.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package tree; import java.util.List; public class NodeImpl<E> implements Node<E> { private E value; private List<Node<E>> children; public NodeImpl(E value, List<Node<E>> children) { this.value = value; this.children = children; } public E getValue() { return value; } public List<Node<E>> getChildren() { return children; } } |
Here is…