二叉树节点计数有问题

时间:2019-05-14 19:14:38

标签: c++ binary-tree

在公共环境中调用Node Counting函数时,我得到了不兼容的声明,而在私有环境中,我的返回值与该函数不匹配,因此无法在测试驱动程序中进行调用。

浮点数,整数,空值,布尔值(我知道这很愚蠢)。

CPP

void BinaryTree::count(TreeNode* root) {
if(root == NULL)
    return 0;
else 
    if(root->left == NULL && root->right == NULL)
        return 1;
    else
        return count(root->left) + count(root->right) + 1;    
}

标头(我想我需要将此标头公开,以便我可以调用测试驱动程序,但是我只能在Private中的CPP中声明。)

void count(TreeNode *);

驱动程序

cout << "Total Number of Nodes " << endl;
tree.count();
cout << endl;

在驱动程序测试中CPP tree.count是不可访问的,这是可以理解的,因为它是从私有调用的,但是作为公共调用,声明是不兼容的。

1 个答案:

答案 0 :(得分:2)

void BinaryTree::count(TreeNode* root) {
  if(root == NULL)
   return 0;
  else 
   if(root->left == NULL && root->right == NULL)
       return 1;
   else
       return count(root->left) + count(root->right) + 1;    
}

该操作返回一个 int (至少一个数字),它必须具有一个返回数字的签名,例如

int BinaryTree::count(TreeNode* root) 

您的定义也很复杂,可以做到

 int BinaryTree::count(TreeNode* root) {
   return (root == NULL)
     ? 0
     : count(root->left) + count(root->right) + 1;    
 }

并且由于它不会修改实例,因此使其成为const

 int BinaryTree::count(TreeNode* root) const {
   return (root == NULL)
     ? 0
     : count(root->left) + count(root->right) + 1;    
 }

拥有

  

tree.count();

没有arg并明显地写出计数,您需要其他操作,如

void BinaryTree::count() const {
  cout << count(..the tree node..);
}

该操作必须是公开的,可能上一个是私有的

无论如何,最好不要写计数,而要返回计数,让调用者随心所欲。

所以最终像这样:

// I use a _struct because fields accessible by BinaryTree
// but  may be a class and BinaryTree is a friend class etc
struct TreeNode {
  // ...
  TreeNode * left;
  TreeNode * right;
  // ...
};

class BinaryTree {
  public:
    // ...
    int count() const { return count(tree); }
    // ...
  private:
    // ...
    int count(TreeNode *) const;
    // ...
    TreeNode * tree;
    // ...
};

int BinaryTree::count(TreeNode* root) const {
   return (root == NULL)
     ? 0
     : count(root->left) + count(root->right) + 1;    
 }

cout << "Total Number of Nodes " << tree.count() << endl;某处

相关问题