这是我的参考树:
3
/
5 2
/ /
1 4 6
下面是递归方法的预期输出:
(1*3) + (2 * (5 + 2)) + (3 * (1 + 4 + 6)) = 50
…下面是我到目前为止的代码:
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
}
}
我知道我可能要调用自己并增加someDepth,但我似乎不能做到这一点。什么好主意吗?
你的意思大概是:
return someDepth * someNode.data +
depthSum(someNode.left, someDepth+1) +
depthSum(someNode.right, someDepth+1);