Ted*_*dyG 0 java binary-tree count nodes
我在计算二叉树中的节点时遇到问题.这是一个真正的简单树,如下图所示.
(5)
(3)-------^-------(7)
(2)---^---(6) ^-------(9)
(5)---^---(8)
Run Code Online (Sandbox Code Playgroud)
我添加了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);
}
Run Code Online (Sandbox Code Playgroud)
它必须在某个地方错过一个计数,但我不确定它在哪里发生.你能帮帮我吗?谢谢.
| 归档时间: |
|
| 查看次数: |
3019 次 |
| 最近记录: |