Here is my reference tree:

    3
   / \
  5   2
 /   / \
1   4   6

Here is the expected output of the recursive method:

(1*3) + (2 * (5 + 2)) + (3 * (1 + 4 + 6)) = 50

...and here is the code I have thus far:

public int depthSum()
{
    int depth = 1;
    return depthSum(overallRoot, depth);
}

public int depthSum(IntTreeNode someNode, int someDepth)
{
    if(someNode == null)
    {
        return 0;
    }
    else
    {
        return someDepth * someNode.data + //some recursion
    }
}

I get that I have to likely call myself and increment someDepth, but I can't seem to get this right. Any ideas?

share|improve this question

1 Answer

up vote 3 down vote accepted

Presumably you mean:

return someDepth * someNode.data +
       depthSum(someNode.left, someDepth+1) +
       depthSum(someNode.right, someDepth+1);
share|improve this answer
I was convinced I had to do something like (depth+1 * depthSum(someNode.left, someDepth+1) ... – Pat K 24 mins ago
@PatK Hopefully you can now see why that is incorrect. – paddy 21 mins ago

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.