【问题标题】:Recursive call without global variables or function parameters没有全局变量或函数参数的递归调用
【发布时间】:2017-10-03 04:35:37
【问题描述】:

所以我们有一个作业来计算二叉搜索树中的节点,但是我们不允许使用全局变量或函数参数,因为我们得到了一个我们不应该更改的预制模板。我知道如何使用全局变量和函数参数来做到这一点,但没有它我不知道如何做到这一点,因为我不能使用局部变量。

我现在的代码:

int count() const
        {
            int st = 1;
            if (left != NULL) {
                st++;
                left->count();
            }
            if (right != NULL) {
                st++;
                right->count();
            }
            return st;
        }

【问题讨论】:

  • 不允许使用全局变量或局部函数变量?

标签: c++ recursion binary-tree


【解决方案1】:

您可以总结通过递归调用各个子树(如果可用)提供的返回值:

    int count() const
    {
        if (left != NULL && right != NULL)
           return 1+left->count()+right->count();
        else if (left != NULL)
           return 1+left->count();
        else if (right != NULL)
           return 1+right->count();
        else
           return 1;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多