【发布时间】:2020-06-10 03:06:57
【问题描述】:
我不知道如何在整数的二叉搜索树中找到整数的平均值。
如果树是空的,它应该返回 0。
到目前为止我的代码是:
//Node class
class Node
{
public:
private:
int data;
Node* left;
Node* right;
friend class BST;
};
Binary Search Tree class
class BST
{
public:
Node* insert(int value, Node* root)
{
if (root == NULL)
{
root = new Node;
root->data = value;
root->left = root->right = NULL;
}
else if (value < root->data)
{
root->left = insert(value, root->left);
}
else if (value > root->data)
{
root->right = insert(value, root->right);
}
return root;
}
void insert(int x)
{
root = insert(x, root);
}
int sum(Node* root) {
if (root == NULL)
{
return 0;
}
return root->data + sum(root->right) + sum(root->left);
}
int count(Node* root)
{
if (root == NULL)
{
return 0;
}
return count(root->right) + count(root->left) + 1;
}
double average(Node* root) {
return (double)sum(root) / count(root);
}
private:
Node* root;
};
int main()
{
BST tree;
tree.insert(20);
tree.insert(25);
tree.insert(15);
tree.insert(10);
tree.insert(30);
tree.insert(0);
cout << tree.average(root) << endl; // this gives an error
}
我添加了一些辅助函数,但如果其中有任何错误,请告诉我..
当我调用 average() 函数时,它给了我一个错误。我想我需要 sum() 函数和 count() 函数。如果 count() 为 0,则平均值为 0。然后 average() 函数将只是将总和除以计数。
【问题讨论】:
-
调用
average时遇到什么错误? -
"标识符根未定义"
-
average为什么要争论?count和sum是有意义的,因为它们是递归的,但average不是。
标签: c++ binary-search-tree average