Skip to content

Commit f843a6a

Browse files
Naman Yadavabranhe
authored andcommitted
Kth Ancestor a Tree Node using Binary Lifting technique
1 parent a44885a commit f843a6a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//Kth Ancestor of a treenode using Binary Lifting. If kth ancestor does not exist, return -1. Implemented in C++17
2+
// author : github.com/yadavnaman
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
class TreeAncestor {
7+
8+
public:
9+
vector< vector<int> >dp; // dp[i][node] : node's 2^i parent
10+
int n;
11+
TreeAncestor(int m, vector<int>& parent) {
12+
n = m;
13+
dp.resize(20,vector<int> (m,-1));
14+
for(int node = 0 ; node < parent.size(); ++node){
15+
dp[0][node] = parent[node];
16+
}
17+
// 2^i parent
18+
for(int i = 1; i< 20; ++i) {
19+
for(int node = 0 ; node < parent.size(); ++node) {
20+
int node_par = dp[i-1][node];
21+
if(node_par != -1){
22+
dp[i][node] = dp[i-1][node_par];
23+
}
24+
}
25+
}
26+
27+
}
28+
29+
int getKthAncestor(int node, int k) {
30+
for(int i = 0; i < 20; ++i) {
31+
if(k & (1<<i)) {
32+
node = dp[i][node];
33+
if(node == -1){
34+
return -1;
35+
}
36+
}
37+
}
38+
return node;
39+
}
40+
};
41+
42+
int main() {
43+
int m,k,node;
44+
cin >> m >> k;
45+
vector<int> par(m);
46+
for(int i = 0; i < m; ++i){
47+
cin>>par[i];
48+
}
49+
cin >> node;
50+
TreeAncestor* obj = new TreeAncestor(m,par);
51+
cout << obj->getKthAncestor(node,k) <<"\n";
52+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy