简体   繁体   中英

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);
}

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 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM