[英]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() function 时,它给我一个错误。 我想我需要 sum() function 和 count() function。如果 count() 为 0,则平均值为 0。然后 average() function 将只是将总和除以计数。
您的average
function 根本不需要参数。 你可以简单地做:
double average()
{
return static_cast<double>(sum(root)) / count(root); // uses the actual root
}
并这样称呼它:
cout << tree.average() << endl;
我这样做的方法是让包装器 function 调用递归 function。递归 function 可以有两个变量,它们通过引用传递总和和金额。 这样你只需要为两个值遍历一次。
这是包装器 function:
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;
}
以及正在调用的递归 function:
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
调用它,它将返回平均值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.