如何在二叉搜索树节点中查找次要元素的平均值
How to find average of secondary element in a Binary Search Tree node
>我正在尝试创建一个函数来查找树节点中某些数据的平均值。问题是,每个节点都包含两条数据,与其他 BST 不同,构建它的主要数据是一个字符串。在树中找到基于数字的元素的平均值对我来说不是问题,但由于每个节点都包含一个字符串(一个人的名字)和一个看似随机的数字(所述人的权重),树实际上完全混乱,我不知道如何处理它。这是我的节点,所以你明白我的意思:
struct Node {
string name;
double weight;
Node* leftChild;
Node* rightChild;
};
Node* root;
以下是其多个阶段之一的函数:
// This isn't what I'm actually using so don't jump to conclusions
double nameTree::averageWeight(double total, double total, int count) const
{
if (parent != NULL)
{ //nonsense, nonsense
averageWeight(parent->leftChild, total, count);
averageWeight(parent->rightChild, total, count);
count++;
total = total + parent->weight;
return total;
}
return (total / count);
}
为了遍历树,我尝试了一些递归,但每次我设法计算和汇总所有内容时,都会出现问题,最终每次都返回(total/count)。我还尝试通过遍历树并将权重添加到数组来实现数组,但这不起作用,因为返回和递归干扰了什么。
只是因为我知道有人会问,是的,这是学校作业。但是,这是一个类中的 18 个函数,所以我并没有要求任何人为我做这件事。我已经在这个功能上呆了几个小时了,我已经整夜未眠,我的大脑很痛,所以任何帮助将不胜感激!
你可以尝试这样的事情:
//total number of tree nodes
static int count=0;
// Calculate the total sum of the weights in the tree
double nameTree::calculateWeight(Node *parent)
{
double total=0;
if (parent != NULL)
{
//nonsense, nonsense
//Calculate total weight for left sub-tree
total+=calculateWeight(parent->leftChild);
//Calculate weight for right sub-tree
total+=calculateWeight(parent->rightChild);
//add current node weight
total+=parent->weight;
}
count++;
//if it is a leaf it will return 0
return total;
}
double averageWeight()
{
double weightSum;
weightSum=calculateWeight();
if(count!=0)
return (weightSum/count);
else
{
cout<<"The tree is empty";
return 0;
}
}
我这里没有编译器,但我相信它可以工作。
要计算平均值,您需要两个数字:总值和集合中元素的数量。您需要提供一个函数(递归可能是最简单的),该函数将遍历树并返回具有这些值的pair<double,int>
,或者修改作为引用传递的某些参数以存储两个值。
对于您的代码,averageWeight
返回一个double
,但是当您递归调用它时,您将忽略(丢弃)结果。count
参数是通过 copy 传递的,这意味着递归调用中应用的修改对调用方不可见(然后调用方不知道parent->weight
对结果的权重是多少。
这应该足以让你开始。
相关文章:
- 在对向量中查找元素的索引
- 在链接列表中查找元素 - C++
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 用于查找元素的数据结构
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 在二叉搜索树中查找元素
- 二进制搜索不变以查找元素的首次出现
- 迭代列表以查找元素的出现.代码问题
- 从单链接列表(从尾部)中查找元素
- iMacro 查找元素
- 在向量数组中查找元素
- 如何在二叉搜索树中查找元素
- 如何在字符右侧的QString中查找元素
- 在Vector中查找元素对
- 如何在运行时在boost::fusion::vector中查找元素
- 在 stl 堆栈 cpp 中查找元素
- 在向量中查找元素并将其删除
- 如何在动态数组中查找元素的数量
- 在数组中查找元素,然后使用指针进行交换