思想
- 如果每个结点,都保存了它所有的祖先结点,最终时间复杂度或者空间复杂度都会爆,导致无法通过测试样例
- 因此,想办法把
O
(
n
)
O(n)
O(n)变成
O
(
log
n
)
O(\log n)
O(logn)就能做出来了
- 让每个结点只保存一部分祖先,然后通过互相之间的关系,从而得到全部的信息
- 即,让每个结点保存它的第1,2,4,8…个祖先
代码
class TreeAncestor {
public:
vector<vector<int> > P; // P[i][node] :::: [node] 's [2^i]th parent
TreeAncestor(int n, vector<int>& parent) {
// initialize
P.resize(20, vector<int>(parent.size(), -1));
// 2^0
for(int i = 0; i < parent.size(); i++){
P[0][i] = parent[i];
}
// 2^i
for(int i = 1; i < 20; i++){
for(int node = 0; node < parent.size(); node ++){
int nodep = P[i-1][node];
if(nodep != -1) P[i][node] = P[i-1][nodep];
}
}
}
int getKthAncestor(int node, int k) {
for(int i = 0; i < 20; i++){
if(k & (1 << i)){
node = P[i][node];
if(node == -1) return -1;
}
}
return node;
}
};
参考
Leetcode discuss