在二叉搜索树C++中计算平均值
Compute average in Binary Search Tree C++
我陷入了如何在整数的二叉搜索树中找到整数的平均值的困境。
如果树为空,则应返回 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
函数根本不需要参数。您可以简单地执行以下操作:
double average()
{
return static_cast<double>(sum(root)) / count(root); // uses the actual root
}
并像这样称呼它:
cout << tree.average() << endl;
我这样做的方法是让包装函数调用递归函数。递归函数可以有两个变量,它们通过引用传递总和和金额。这样,您只需对两个值遍历一次。
这是包装器函数:
double average(node * root) {
if(!root) {
return 0; //base case if the tree is empty
}
int sum = 0; //variable for holding the sum
int amount = 0; //variable for holding the amount of data
averageRecursive(root, sum, amount); //calling the recursive function
return (double)sum/amount;
}
以及正在调用的递归函数:
void averageRecursive(node * root, int &sum, int &amount) {
if(!root)
return; //base case when we reach a node thats empty
countAverage(root->left, sum, amount); //going to the left
sum += root->data; //adding currents invocations root data to the sum
++amount; //adding one to the amount counter
countAverage(root->right, sum, amount); //going to the right
}
然后,您将从带有tree.average()
的main
调用它,它将返回平均值。
相关文章:
- 计算平均值,不包括上次得分
- 在二叉搜索树C++中计算平均值
- 计算平均值:蒙版图像与投资回报率的不同结果
- 类型检测:使用variadic参数正确实现计算平均值的函数
- C 平均程序在循环时不计算n后不计算平均值
- 我必须将 5 个数字放入一个数组中,而不是 cin 计算平均值并输出它,我做错了
- 我需要知道如何正确计算平均值和偏差
- 从数组中获取值并计算平均值,然后存储在数组中
- 发布获取语义以计算平均值
- 计算平均值,而不向退出循环添加负等级
- 如何正确使用指针来计算平均值
- 如何计算平均值
- 在没有值时跳过计算平均值.C++.Xcode
- 用c++计算平均值和方差
- 用于计算平均值的C++程序
- 高精度计算平均值的最佳策略
- 计算平均值C++
- 程序不会降低最低分数并在没有它的情况下计算平均值
- 我需要将Valus与字符串关联的帮助才能计算平均值
- 如何使用 std::累积 和 lambda 来计算平均值