簡體   English   中英

樹中兩片葉子的最低共同祖先

[英]Lowest common ancestor of two leaves in a tree

我有以下樹結構:

struct Node {
   int data;
   Node* parent = nullptr;
}

每個節點最多有一個父節點,但可以有多個子節點。 我試圖找到沒有任何孩子的兩個節點(節點 1 和節點 2)的最低共同祖先。

這是我當前的代碼:

std::vector<Node*> ancestors1;
std::vector<Node*> ancestors2;
temp_node = node1->parent;
while(temp_node!=nullptr) {
    ancestors1.push_back(temp_node);
    temp_node = temp_node->parent;
}
temp_node = node2->parent;
while(temp_node!=nullptr) {
    ancestors2.push_back(temp_node);
    temp_node = temp_node->parent;
}
Node* common_ancestor = nullptr;
if (ancestors1.size() < ancestors2.size()) {
    ptrdiff_t t = ancestors1.end() - ancestors1.begin();
    std::vector<Node*>::iterator it1 = ancestors1.begin();
    std::vector<Node*>::iterator it2 = ancestors2.end() - t;
    while(it1!=ancestors1.end()) {
        if (*it1 == *it2) {
            common_ancestor = *it1;
        }
        ++it1;
    }
} else {
    ptrdiff_t t = ancestors2.end() - ancestors2.begin();
    std::vector<Node*>::iterator it2 = ancestors2.begin();
    std::vector<Node*>::iterator it1 = ancestors1.end() - t;
    while(it2!=ancestors2.end()) {
        if (*it1 == *it2) {
            common_ancestor = *it1;
        }
        ++it2;
    }
}
return common_ancestor

這段代碼並不總是有效,我不知道為什么。

對不起,我忍不住了。

除了錯別字和錯誤,我相信它看起來更簡單:

#include <cassert>
#include <algorithm>
#include <iostream>
#include <vector>

struct Node {
  int data;
  Node *parent = nullptr;
};

Node* findCommonAncestor(Node *pNode1, Node *pNode2)
{
  // find paths of pNode1 and pNode2
  std::vector<Node*> path1, path2;
  for (; pNode1; pNode1 = pNode1->parent) path1.push_back(pNode1);
  for (; pNode2; pNode2 = pNode2->parent) path2.push_back(pNode2);
  // revert paths to make indexing simple
  std::reverse(path1.begin(), path1.end());
  std::reverse(path2.begin(), path2.end());
  // compare paths
  Node *pNode = nullptr; // ancestor
  size_t n = std::min(path1.size(), path2.size());
  for (size_t i = 0; i < n; ++i) {
    if (path1[i] == path2[i]) pNode = path1[i];
    else break;
  }
  // done
  return pNode;
}

int main()
{
  // sample tree:
  /*     1
   *     |
   *     2
   *    / \
   *   3   4
   *       |
   *       5
   */
  Node node1 = { 1, nullptr };
  Node node2 = { 2, &node1 };
  Node node3 = { 3, &node2 };
  Node node4 = { 4, &node2 };
  Node node5 = { 5, &node4 };
  Node *pNode = findCommonAncestor(&node3, &node5);
  if (pNode) {
    std::cout << "Lowest common ancestor: " << pNode->data << '\n';
  } else {
    std::cout << "No common ancestor found!\n";
  }
}

輸出:

Lowest common ancestor: 2

在coliru上進行現場演示

筆記:

雖然使用iterator有助於保持代碼的通用性……

我認為這是堅持使用普通舊數組(又名std::vector )索引可以簡化事情的情況之一。

我發現了問題。 除了需要移動兩個迭代器而不是一個(感謝 Jarod42 和 v78),我還需要在找到最低的公共祖先時立即跳出 while 循環(否則它返回最高的公共祖先)。

while(it1!=ancestors1.end()) {
        if (*it1 == *it2) {
            common_ancestor = *it1;
            break;
        }

你應該不需要任何額外的空間來解決這個問題:

// measure depths
size_t depth1=0;
for (Node *n = node1; n; n=n->parent, ++depth1);
size_t depth2=0;
for (Node *n = node2; n; n=n->parent, ++depth2);

// move the deeper one up until they're the same depth
for (;depth1 > depth2; node1 = node1->parent, --depth1);
for (;depth2 > depth1; node2 = node2->parent, --depth2);

// move them both up until they match
while(node1 != node2) {
    node1 = node1->parent;
    node2 = node2->parent;
}

return node1;

暫無
暫無

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

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