-
Notifications
You must be signed in to change notification settings - Fork 1
/
9_12_LCA_with_parent_pointers
124 lines (107 loc) · 2.23 KB
/
9_12_LCA_with_parent_pointers
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
template <typename T>
class node {
public:
T data;
node *left, *right, *parent;
node() {
left = right = parent = NULL;
}
};
template <typename T>
class BinaryTree {
public:
node<T> *root;
BinaryTree() {
root = NULL;
}
void _insert(T a, node<T> *n) {
if (root) {
if (a < n->data) {
if (n->left)
_insert(a, n->left);
else {
node<T> *leaf = new node<T>();
leaf->data = a;
leaf->parent = n;
n->left = leaf;
}
}
else {
if (n->right)
_insert(a, n->right);
else {
node<T> *leaf = new node<T>();
leaf->data = a;
leaf->parent = n;
n->right = leaf;
}
}
}
else {
node<T> *leaf = new node<T>();
leaf->data = a;
root = leaf;
}
}
void insert(T a) {
_insert(a, root);
}
node<T>* leastCommonAncestor(node<T>* a, node<T>* b) {
int h1 = 0, h2 = 0;
node<T> *ancestorA = a->parent, *ancestorB = b->parent;
while (ancestorA) {
h1++;
ancestorA = ancestorA->parent;
}
while (ancestorB) {
h2++;
ancestorB = ancestorB->parent;
}
while (h1 > h2) {
a = a->parent;
h1--;
}
while (h2 > h1) {
b = b->parent;
h2--;
}
while (a != b) {
a = a->parent;
b = b->parent;
}
return a;
}
void Print (node<T> * x, int & id)
{
if (!x) return;
Print (x->left,id);
id++;
cout << id << ' ' << x->data << endl;
Print (x->right,id);
}
};
int main() {
BinaryTree<int> B;
B.insert(10);
B.insert(5);
B.insert(13);
B.insert(16);
B.insert(11);
B.insert(7);
B.insert(3);
B.insert(6);
B.insert(8);
B.insert(9);
cout << "Find LCA of " << B.root->left->right->left->data << " and " << B.root->left->right->right->right->data << endl;
node<int>* n = B.leastCommonAncestor(B.root->left->right->left, B.root->left->right->right->right);
cout << n->data << endl;
return 0;
}