简体   繁体   中英

Updating a pointer value with an integer during a recursive call in postorder traversal of a BST

int MovieTree::countMovieNodes()
{
    int count = 0;
    int* c = &count;
    countMovieNodes(root,c);
    return *c;
}
void MovieTree::countMovieNodes(MovieNode *node, int *c)
{
    int count;
    if(node == NULL)
    {
        return;
    }
    else
    {
        count ++;
        countMovieNodes(node->leftChild, c);
        countMovieNodes(node->rightChild, c);
    }

}

My code is returning 0, so clearly I am misunderstanding the methodology to updating the pointer values. How do I fix this? I don't think my logic for post order traversal of the BST is the issue.

If you want to keep your current format, creating a new count is still making of copy of it, just incerment the pointer directly:

int MovieTree::countMovieNodes()
{
    int count = 0;
    int* c = &count;
    countMovieNodes(root,c);
    return *c;
}
void MovieTree::countMovieNodes(MovieNode *node, int *c)
{
    if(node == NULL)
    {
        return;
    }
    else
    {
        ++*c;
        countMovieNodes(node->leftChild, c);
        countMovieNodes(node->rightChild, c);
    }
}

Your code doesn't actually use the c parameter (it just passes it on to recursive calls, which also don't use c ). Your code also creates a local count variable in each call, which is only incremented (not written to or read from).

What you should do instead is

  1. delete int count;
  2. change count ++; to (*c)++; (or *c += 1; if you don't like parens) to increment the count variable in the top-level countMovieNodes() call)

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