class TreeAncestor {
public:
TreeAncestor(int n, vector<int>& parent) {
}
int getKthAncestor(int node, int k) {
}
};
/**
* Your TreeAncestor object will be instantiated and called as such:
* TreeAncestor* obj = new TreeAncestor(n, parent);
* int param_1 = obj->getKthAncestor(node,k);
*/
type TreeAncestor [][]int
func Constructor(n int, parent []int) TreeAncestor {
m := bits.Len(uint(n))
pa := make([][]int, n)
for i, p := range parent {
pa[i] = make([]int, m)
pa[i][0] = p
}
for i := 0; i < m-1; i++ {
for x := 0; x < n; x++ {
if p := pa[x][i]; p != -1 {
pa[x][i+1] = pa[p][i]
} else {
pa[x][i+1] = -1
}
}
}
return pa
}
func (pa TreeAncestor) GetKthAncestor(node, k int) int {
m := bits.Len(uint(k))
for i := 0; i < m; i++ {
if k>>i&1 > 0 { // k 的二进制从低到高第 i 位是 1
node = pa[node][i]
if node < 0 {
break
}
}
}
return node
}
// 另一种写法,不断去掉 k 的最低位的 1
func (pa TreeAncestor) GetKthAncestor2(node, k int) int {
for ; k > 0 && node != -1; k &= k - 1 {
node = pa[node][bits.TrailingZeros(uint(k))]
}
return node
}
/**
* Your TreeAncestor object will be instantiated and called as such:
* obj := Constructor(n, parent);
* param_1 := obj.GetKthAncestor(node,k);
*/
class TreeAncestor {
private int[][] pa;
public TreeAncestor(int n, int[] parent) {
int m = 32 - Integer.numberOfLeadingZeros(n); // n 的二进制长度
pa = new int[n][m];
for (int i = 0; i < n; i++)
pa[i][0] = parent[i];
for (int i = 0; i < m - 1; i++) {
for (int x = 0; x < n; x++) {
int p = pa[x][i];
pa[x][i + 1] = p < 0 ? -1 : pa[p][i];
}
}
}
public int getKthAncestor(int node, int k) {
int m = 32 - Integer.numberOfLeadingZeros(k); // k 的二进制长度
for (int i = 0; i < m; i++) {
if (((k >> i) & 1) > 0) { // k 的二进制从低到高第 i 位是 1
node = pa[node][i];
if (node < 0) break;
}
}
return node;
}
// 另一种写法,不断去掉 k 的最低位的 1
public int getKthAncestor2(int node, int k) {
for (; k > 0 && node != -1; k &= k - 1)
node = pa[node][Integer.numberOfTrailingZeros(k)];
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);
*/
class TreeAncestor:
def __init__(self, n: int, parent: List[int]):
m = n.bit_length() - 1
pa = [[p] + [-1] * m for p in parent]
for i in range(m):
for x in range(n):
if (p := pa[x][i]) != -1:
pa[x][i + 1] = pa[p][i]
self.pa = pa
def getKthAncestor(self, node: int, k: int) -> int:
for i in range(k.bit_length()):
if (k >> i) & 1: # k 的二进制从低到高第 i 位是 1
node = self.pa[node][i]
if node < 0: break
return node
# 另一种写法,不断去掉 k 的最低位的 1
def getKthAncestor2(self, node: int, k: int) -> int:
while k and node != -1: # 也可以写成 ~node
lb = k & -k
node = self.pa[node][lb.bit_length() - 1]
k ^= lb
return node
# Your TreeAncestor object will be instantiated and called as such:
# obj = TreeAncestor(n, parent)
# param_1 = obj.getKthAncestor(node,k)