【问题标题】:Finding the path of the minimum in a tree在树中找到最小值的路径
【发布时间】:2012-07-19 03:20:40
【问题描述】:

这是我研究代码中的一个问题,我想知道执行此操作的有效方法是什么。我省略了不必要的细节,并以一种可以理解问题症结的方式呈现它。

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

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。在对现有函数进行最小更改的情况下,执行此操作的有效方法是什么?通过最小的更改,我的意思是我可以添加额外的变量来跟踪分支,但不能完全重写函数。

谢谢

【问题讨论】:

  • 你的树有parent 链接吗?还是只有leftright 链接?

标签: c++ algorithm tree


【解决方案1】:

您可以使用列表或堆栈或队列来代替向量:

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

【讨论】:

  • 谢谢。这正是我所需要的。
【解决方案2】:

您可以使用列表/队列作为额外参数来跟踪所选节点:

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

【讨论】:

  • 基本正确但重要的是要注意该列表应作为引用类型传递。
  • 这不起作用,对 minimum 的两个调用都在修改同一个列表,它将包含两个子树的路径。
  • 更好 :),但现在您将一个列表 push_back-ing 到相同类型的列表上。您还需要将当前节点添加到列表中的某个位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2013-06-26
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多