-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
65 lines (55 loc) · 1.45 KB
/
tree.cpp
File metadata and controls
65 lines (55 loc) · 1.45 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
58
59
60
61
62
63
64
65
#include "tree.h"
template<class type>
Tree<type>::Tree(vector<TreeItem<type> *> *elems, TreeItem<type> *root)
{
m_items = elems;
buildTree(root, root, 1);
}
template<class type>
TreeItem<type> *Tree<type>::lca(TreeItem<type> *item1, TreeItem<type> *item2)
{
TreeItem<type> *botItem, *topItem;
if(item1->depth() > item2->depth()){
topItem = item2;
botItem = item1;
}
else{
topItem = item1;
botItem = item2;
}
int depth = abs(int(item1->depth() - item2->depth()));
for(int i = 0; i < depth; i++){
botItem = botItem->parent();
}
while(botItem != topItem){
botItem = botItem->parent();
topItem = topItem->parent();
}
return topItem;
}
template<class type>
size_t Tree<type>::distance(TreeItem<type> *item1, TreeItem<type> *item2)
{
TreeItem<type> *lcaItem = lca(item1, item2);
return abs(int(lcaItem->depth() - item1->depth())) + abs(int(lcaItem->depth() - item2->depth()));
}
template<class type>
size_t Tree<type>::distanceThrough(TreeItem<type> *item1, TreeItem<type> *item2, TreeItem<type> *knot)
{
return distance(item1, knot) + distance(item2, knot);
}
template<class type>
void Tree<type>::buildTree(TreeItem<type> *root, TreeItem<type> *current, int depth)
{
vector<TreeItem<type> *> child = current->child();
size_t sz = child.size();
current->setDepth(depth);
current->setParent(root);
for(size_t i = 0; i < sz; i++){
if(root == child[i]){
current->delChild(i);
continue;
}
buildTree(current, child[i], depth + 1);
}
}