2017-05-04 198 views
-1

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

我现在代码:

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

你不准使用全局变量还是局部函数变量? – sithereal

回答

2

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

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; 
    } 
+0

解决了它。 – hypr2