在树中查找最小值的路径

Finding the path of the minimum in a tree

本文关键字:路径 最小值 查找      更新时间:2023-10-16

这是我的研究代码中的一个问题,我想知道做这件事的有效方法是什么。我省略了不必要的细节,我以一种能够理解问题症结的方式来介绍它。

假设我有一个二叉树,每个节点上都有数字。我想找到树上从根到叶的所有分支的最小和。下面是一个非常粗略的伪代码。

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;
   }
}