这是我的引用树:
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);
关于java - 按深度加权的整数二叉树中的求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15468346/