Leetcode 1483. 樹節點的第 K 個祖先【倍增法】

問題描述

給你一棵樹,樹上有 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 因爲不存在滿足要求的祖先節點

提示:

1<=k<=n<=51041 <= k <= n <=5*10^4
parent[0]==1parent[0] == -1 表示編號爲 0 的節點是根節點。
對於所有的 0<i<n0<=parent[i]<n0 < i < n ,0 <= parent[i] < n 總成立
0<=node<n0 <= node < n
至多查詢 51045*10^4

解題報告

因爲是多次查詢 getKthAncestor(int node, int k),如果每次執行查詢,效率太低了,所以提前將結果存在二維數組中,之後直接 O(1) 的時間複雜度進行查詢。
dp[i][j] 表示節點 i 的第 2j2^j 號祖父。
所以 dp[i][j]=dp[dp[i][j1]][j1]      if  dp[i][j1]!=1dp[i][j]=dp[dp[i][j-1]][j-1]\;\;\;if \;dp[i][j-1]!=-1

實現代碼

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);
 */

參考資料

[1] Leetcode 1483. 樹節點的第 K 個祖先

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章