计算二叉树中的节点

时间:2013-03-15 01:05:37

标签: java count binary-tree nodes

我在计算二叉树中的节点时遇到问题。这是一个真正的简单树,如下图所示。

                                (5)
                       (3)-------^-------(7)
                  (2)---^---(6)           ^-------(9)
                       (5)---^---(8)

我添加了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);
}

它必定在某个地方错过了一个计数,但我不确定它在哪里发生。你能帮帮我吗?感谢。

1 个答案:

答案 0 :(得分:5)

我认为问题是numNodes是一个类成员,它应该是方法的局部变量。