LCA后代节点
LCA descendant nodes
我试图获得树中两个节点的最小共同祖先。我试过了,但问题是if one node is the descendant node for other
我无法得到LCA。
我试着解决它,然后它只适用于后代节点。我不知道该怎么做。
Node* Tree::LCA(Node* root, Node* n1, Node* n2) {
list<Node*> a1,a2;
while(n1 != NULL) {
a1.push_back(n1->parent);
n1 = n1->parent;
}
while(n2 != NULL) {
a2.push_back(n2->parent);
n2 = n2->parent;
}
while(!a1.empty() && !a2.empty() && a1.back() == a2.back()) {
a1.pop_back();
a2.pop_back();
}
if( a1.back() != a2.back()) {
Node* rn = a1.back();
cout << " LCA of r-U and r_v is " << rn->index << endl;
}
}
从n1->parent
和n2->parent
开始推。相反,在推他们的父母和其他祖先之前,也推n1
和n2
。所以你的代码应该是:
Node* Tree::LCA(Node* root, Node* n1, Node* n2) {
list<Node*> a1,a2;
a1.push_back(n1); // line to be added
while(n1 != NULL) {
a1.push_back(n1->parent);
n1 = n1->parent;
}
a2.push_back(n2); // line to be added
while(n2 != NULL) {
a2.push_back(n2->parent);
n2 = n2->parent;
}
// rest of code
Node* Tree::LCA(Node* root, Node* n1, Node* n2) {
list<Node*> a1,a2;
while(n1 != NULL) {
a1.push_back(n1); // push n1
n1 = n1->parent;
}
while(n2 != NULL) {
a2.push_back(n2); // push n2
n2 = n2->parent;
}
Node* old; // create new node
while(!a1.empty() && !a2.empty() && a1.back() == a2.back()) {
old = a1.back(); // store the node before popping
a1.pop_back();
a2.pop_back();
}
if( a1.back() != a2.back()) {
// Node* rn = a1.back(); //not needed
cout << " LCA of r-U and r_v is " << old->index << endl; // changed
}
}
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- 引擎节点:未定义的符号:_ZTV6Config
- 为什么"delete"关键字不删除节点?
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 如何按数字顺序插入链表节点?
- 如何编写对树中节点的后代进行计数的迭代DFS
- LCA后代节点