在树中查找最小值的路径
Finding the path of the minimum in a tree
这是我的研究代码中的一个问题,我想知道做这件事的有效方法是什么。我省略了不必要的细节,我以一种能够理解问题症结的方式来介绍它。
假设我有一个二叉树,每个节点上都有数字。我想找到树上从根到叶的所有分支的最小和。下面是一个非常粗略的伪代码。
int minimum(tree){
// Some base cases
left_min = minimum(tree->left);
right_min= minimum(tree->right);
if (left_min < right_min){
return current_value + left_min;
}
else{
return current_value + right_min;
}
}
由此,我可以计算出最小值。然而,如果我想计算给我最小值的节点,我该怎么办?即,如果答案是14,我想找出树中每个级别的哪些节点加起来给我一个14的和。在对现有功能进行最小更改的情况下,实现这一目标的有效方法是什么?我的意思是,我可以添加额外的变量来跟踪分支,但不能完全重写函数。
感谢
您可以使用列表、堆栈或队列来代替向量:
typedef vector<yourIdType> idvec;
int minimum(tree, idvec &path){
// Some base cases
idvec leftPath, rightPath;
left_min = minimum(tree->left, leftPath);
right_min= minimum(tree->right, rightPath);
if (left_min < right_min){
swap(path, leftPath);
path.push_back(thisNodeId);
return current_value + left_min;
} else {
swap(path, rightPath);
path.push_back(thisNodeId);
return current_value + right_min;
}
}
您可以使用列表/队列作为额外的参数来跟踪所选节点:
int minimum(tree, list){
List templeft, tempright;
// Some base cases
left_min = minimum(tree->left, templeft);
right_min= minimum(tree->right, tempright);
if (left_min < right_min){
list.push_back(templeft);
list.push_back(current);
return current_value + left_min;
}
else{
list.push_back(tempright);
list.push_back(current);
return current_value + right_min;
}
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- txt 文件中浮点数的最大和最小值
- 余数运算符的等效操作,用于处理低于允许的最小值
- 需要使用模板查找数组的第二个最小和最小值
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 查找包含 N 个元素的数组的最小值和最大值
- 错误C++在Visual Studio 2019中使用numeric_limits的长双精度最小值/最大值
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?
- 如何在 c++ 中创建对的优先级队列.这会弹出具有最小值的元素.默认的弹出最大值
- 将最小值整数转换为无符号长整型
- 查找 std::vector 中的最小值和最大值 std::p air
- 如何找到每行的最大值和最小值
- 在树中查找最小值的路径