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 binary tree?
|
|
package tree; public interface Node<E> { E getValue(); Node<E> getLeft(); Node<E> getRight(); } |
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 23 24 25 26
|
package tree; public class NodeImpl<E> implements Node<E> { private E value; private Node<E> left; private Node<E> right; public NodeImpl(E value, Node<E> left, Node<E> right) { this.value = value; this.left = left; this.right = right; } public E getValue() { return value; } public Node<E> getLeft() { return left; } public Node<E> getRight() { return right; } } |
Here is the getLevelSum(root, … Read more ›...