-
Notifications
You must be signed in to change notification settings - Fork 3
/
1483.cpp
30 lines (28 loc) · 976 Bytes
/
1483.cpp
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
class TreeAncestor {
public:
vector<vector<int>> hierarchyParents;
TreeAncestor(int n, vector<int>& parent) {
hierarchyParents.resize(n, vector<int>(20));
for (int i = 0; i < n; ++i) hierarchyParents[i][0] = parent[i];
for (int j = 1; j < 20; ++j) {
for (int i = 0; i < n; ++i) {
if (hierarchyParents[i][j - 1] == -1) hierarchyParents[i][j] = -1;
else hierarchyParents[i][j] = hierarchyParents[hierarchyParents[i][j - 1]][j - 1];
}
}
}
int getKthAncestor(int node, int k) {
for (int i = 0; i < 20; ++i) {
if ((k >> i) & 1) {
node = hierarchyParents[node][i];
if (node == -1) return -1;
}
}
return node;
}
};
/**
* Your TreeAncestor object will be instantiated and called as such:
* TreeAncestor* obj = new TreeAncestor(n, parent);
* int param_1 = obj->getKthAncestor(node,k);
*/