我在计算二叉树中的节点时遇到问题。这是一棵真正简单的树,如下图所示。
(5)
(3)-------^-------(7)
(2)---^---(6) ^-------(9)
(5)---^---(8)
我添加了八个节点,所以应该有 8 个。但是,当我运行我的代码时,它计算了 7 个节点。我认为它只是计算所有左节点和右节点而不计算根,但我将节点数设置为 1 以在计算左右节点之前计算根。请参阅下面的代码
private int getNumNodes(Node<E> root){
numNodes = 1; // starts by counting the root
// counts the left nodes
if(root.left != null){
numNodes += getNumNodes(root.getLeft());
}
// counts the right nodes
if(root.right != null){
numNodes += getNumNodes(root.getRight());
}
return numNodes;
}
public int getNumNodes(){
return root == null ? 0 : getNumNodes(root);
}
它必须在某处丢失计数,但我不确定它发生在哪里。你们能不能帮帮我。谢谢。