問題描述
給你一棵樹,樹上有 n 個節點,按從 0 到 n-1 編號。樹以父節點數組的形式給出,其中 parent[i] 是節點 i 的父節點。樹的根節點是編號爲 0 的節點。
請你設計並實現 getKthAncestor(int node, int k) 函數,函數返回節點 node 的第 k 個祖先節點。如果不存在這樣的祖先節點,返回 -1 。
樹節點的第 k 個祖先節點是從該節點到根節點路徑上的第 k 個節點。
輸入:
[“TreeAncestor”,“getKthAncestor”,“getKthAncestor”,“getKthAncestor”]
[[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]
輸出:
[null,1,0,-1]
解釋:
TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
treeAncestor.getKthAncestor(3, 1); // 返回 1 ,它是 3 的父節點
treeAncestor.getKthAncestor(5, 2); // 返回 0 ,它是 5 的祖父節點
treeAncestor.getKthAncestor(6, 3); // 返回 -1 因爲不存在滿足要求的祖先節點
提示:
表示編號爲 0 的節點是根節點。
對於所有的 總成立
至多查詢 次
解題報告
因爲是多次查詢 getKthAncestor(int node, int k)
,如果每次執行查詢,效率太低了,所以提前將結果存在二維數組中,之後直接 O(1)
的時間複雜度進行查詢。
dp[i][j]
表示節點 i
的第 號祖父。
所以
實現代碼
class TreeAncestor {
vector<vector<int>> p;
public:
TreeAncestor(int n, vector<int>& parent) {
p = vector<vector<int>>(n, vector<int>(18, -1));
for (int i = 0; i < n; ++i)
p[i][0] = parent[i];
for (int k = 1; k < 18; ++k)
for (int i = 0; i < n; ++i) {
if (p[i][k - 1] == -1)
continue;
p[i][k] = p[p[i][k - 1]][k - 1];
}
}
int getKthAncestor(int node, int k) {
for (int i = 17; i >= 0; --i)
if (k & (1 << i)) {
node = p[node][i];
if (node == -1)
break;
}
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);
*/