I have the following tree structure:
struct Node {
int data;
Node* parent = nullptr;
}
Where each node has at most one parent but can have many children. I am trying to find the lowest common ancestor of two nodes (node1 and node2) who do not have any children.
This is my current code:
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
This code doesn't always work and I'm not sure why.
node2
's ancestros inancestors1
– Jarod42++it1; ++it2;
in both the sides of if-else blocks. – v78it2 = ancestors2.end() - t
- why? both paths must start from root. Couldn't you just iterate both paths from the start and break out as soon as they differ? – 500 - Internal Server Error