获取二叉搜索树中的节点数

com*_*254 1 c++ tree nodes

所以我正在研究一种方法,它可以获得二进制搜索树中的节点数量,当我有3个节点时,它给了我3个,但如果我做了5个它给了我4个,我需要更改什么?

int BinaryTree::size(int count, Node *leaf) const
{
    if(leaf != NULL)//if we are not at a leaf
    {
        size(count + 1, leaf->getLeft());//recurisvly call the function and increment the count
        size(count + 1, leaf->getRight());
    }
    else
    {
        return count;//return the count
    }

}
Run Code Online (Sandbox Code Playgroud)

Nic*_*son 9

int BinaryTree::size(Node *leaf) const 
{
    if(leaf == NULL) { //This node doesn't exist. Therefore there are no nodes in this 'subtree'
        return 0;
    } else { //Add the size of the left and right trees, then add 1 (which is the current node)
        return size(leaf->getLeft()) + size(leaf->getRight()) + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一种不同的方法,但我发现阅读比你拥有的更容易.