我应该实现一个递归方法来计算左子树节点的数量。到目前为止我的代码是:
private int countLeftNodes(IntTreeNode node){
int c = 0;
if (node != null){
c = 1 + countLeftNodes(node.left);
countLeftNodes(node.right);
}
return c;
}
它返回的数字远小于应有的数字。我有一种感觉,我的遍历是关闭的,因为它似乎只计算最左边的子节点,然后终止。当我在大小为 16 的 IntTree 上调用此方法时,我应该得到 8 个左子节点、7 个右子节点和一个根节点,但我得到的是 4 个左子节点。
最佳答案
您永远不会计算右树中的左节点。
private int countLeftNodes(IntTreeNode node)
{
int c = 0;
if (node.left != null)
{
c += 1 + countLeftNodes(node.left);
}
if(node.right != null)
{
c += countLeftNodes(node.right);
}
return c;
}
关于java - 计算树中的左子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5381631/