Skip to content

Commit 5340d72

Browse files
authored
Create 1483-kth-ancestor-of-a-tree-node.js
1 parent fc8c5b5 commit 5340d72

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

1483-kth-ancestor-of-a-tree-node.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[]} parent
4+
*/
5+
var TreeAncestor = function(n, parent) {
6+
// initialize
7+
this.P = Array.from({length: 20}, () => Array(n).fill(-1))
8+
// 2^0
9+
for(let i = 0; i < parent.length; i++){
10+
this.P[0][i] = parent[i];
11+
}
12+
13+
// 2^i
14+
for(let i = 1; i < 20; i++){
15+
for(let node = 0; node < parent.length; node++){
16+
let nodep = this.P[i-1][node];
17+
if(nodep != -1) this.P[i][node] = this.P[i-1][nodep];
18+
}
19+
}
20+
};
21+
22+
/**
23+
* @param {number} node
24+
* @param {number} k
25+
* @return {number}
26+
*/
27+
TreeAncestor.prototype.getKthAncestor = function(node, k) {
28+
for(let i = 0; i < 20; i++){
29+
if(k & (1 << i)){
30+
node = this.P[i][node];
31+
if(node == -1) return -1;
32+
}
33+
}
34+
return node;
35+
};
36+
37+
/**
38+
* Your TreeAncestor object will be instantiated and called as such:
39+
* var obj = new TreeAncestor(n, parent)
40+
* var param_1 = obj.getKthAncestor(node,k)
41+
*/

0 commit comments

Comments
 (0)