-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimized_lca.h
More file actions
57 lines (51 loc) · 1.67 KB
/
Copy pathoptimized_lca.h
File metadata and controls
57 lines (51 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifndef CPP_ALGORITHM_OPTIMIZED_LCA_H
#define CPP_ALGORITHM_OPTIMIZED_LCA_H
#include "binary_tree.h"
#include <stdexcept>
#include <unordered_set>
namespace OptimizedLca
{
/**
* \brief Find the lowest common ancestor of two nodes in a binary tree.
* \details Traverse up node1 and node2 together until they meet.
* \param node1 the first node
* \param node2 the second node
* \return the lowest common ancestor of node1 and node2
*/
const BinaryTree::ExtendedNode<int>* FindOptimizedLowestCommonAncestor(
const BinaryTree::ExtendedNode<int>* node1,
const BinaryTree::ExtendedNode<int>* node2);
}
// ----------------------------------------------------------------------------
inline const BinaryTree::ExtendedNode<int>* OptimizedLca::FindOptimizedLowestCommonAncestor(
const BinaryTree::ExtendedNode<int>* node1,
const BinaryTree::ExtendedNode<int>* node2)
{
auto iter1 = node1;
auto iter2 = node2;
std::unordered_set<const BinaryTree::ExtendedNode<int>*> nodes_on_path;
// traverse up node1 and node2 together until they meet
while (iter1 != nullptr || iter2 != nullptr)
{
if (iter1 != nullptr)
{
if (nodes_on_path.contains(iter1))
{
return iter1;
}
nodes_on_path.insert(iter1);
iter1 = iter1->parent;
}
if (iter2 != nullptr)
{
if (nodes_on_path.contains(iter2))
{
return iter2;
}
nodes_on_path.insert(iter2);
iter2 = iter2->parent;
}
}
throw std::invalid_argument("No common ancestor found.");
}
#endif