user3601198
user3601198

Reputation: 3

Counting nodes in binary search tree

I need to create a recursive method that takes as a parameter the root node of a binary search tree. This recursive method will then return the int value of the total number of nodes that have one left descendant.

int Tree::leftPtrCount(int count) {
    return leftPtrCountHelper(rootPtr, count);
}
int Tree::leftPtrCountHelper(TreeNode *node, int count){
    if (node == NULL)
        return 0;
    if (node->leftPtr != NULL && node->rightPtr == NULL)
        count++;
    else
        return leftPtrCountHelper(node->leftPtr, count) + leftPtrCountHelper(node->rightPtr, count);
}

Upvotes: 0

Views: 218

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

If I understand correctly the assignment then the function will look as

size_t Tree::leftPtrCountHelper( const TreeNode *node )
{
    if ( node == NULL ) return 0;
    return ( node->leftPtr != NULL && node->rightPtr == NULL ) +
             leftPtrCountHelper( node->leftPtr ) + 
             leftPtrCountHelper( node->rightPtr );
}

Upvotes: 1

Related Questions