簡體   English   中英

找到樹中最小值的路徑

[英]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;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM