简体   繁体   English

在BST的后顺序遍历的递归调用期间,使用整数更新指针值

[英]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. 我的代码返回0,因此显然我误解了更新指针值的方法。 How do I fix this? 我该如何解决? I don't think my logic for post order traversal of the BST is the issue. 我认为BST的后遍历逻辑不成问题。

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 ). 您的代码实际上并不使用c参数(它只是将其传递给递归调用,后者也不使用c )。 Your code also creates a local count variable in each call, which is only incremented (not written to or read from). 您的代码还会在每个调用中创建一个本地count变量,该变量只会递增(不会写入或读取)。

What you should do instead is 你应该做的是

  1. delete int count; 删除int count;
  2. change count ++; 更改count ++; to (*c)++; (*c)++; (or *c += 1; if you don't like parens) to increment the count variable in the top-level countMovieNodes() call) (或*c += 1;如果您不喜欢parens)在顶级countMovieNodes()调用中增加count变量)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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