logo Practice-It logo

BJP3 Exercise 17.3: depthSum

Language/Type: Java binary trees implementing IntTree
Related Links:
Author: Robert Baxter (on 2013/04/01)

Write a method depthSum that returns the sum of the values stored in a binary tree of integers weighted by the depth of each value. You should return the value at the overallRoot plus 2 times the values stored at the next level of the tree plus 3 times the values stored at the next level of the tree plus 4 times the values stored at the next level of the tree and so on. For example, in the tree below:

          +---+
          | 9 |
          +---+
         /     \
     +---+     +---+
     | 7 |     | 6 |
     +---+     +---+
    /     \         \
+---+     +---+     +---+
| 3 |     | 2 |     | 4 |
+---+     +---+     +---+
         /               \
     +---+               +---+
     | 5 |               | 2 |
     +---+               +---+

The sum would be computed as:

1 * 9 + 2 * (7 + 6) + 3 * (3 + 2 + 4) + 4 * (5 + 2) = 90

Assume that you are adding this method to the IntTree class as defined below:

public class IntTree {
    private IntTreeNode overallRoot;
    ...
}
Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.