在二叉搜索树C++中计算平均值

Compute average in Binary Search Tree C++

本文关键字:计算 平均值 C++ 搜索树      更新时间:2023-10-16

我陷入了如何在整数的二叉搜索树中找到整数的平均值的困境。

如果树为空,则应返回 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调用它,它将返回平均值。