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 < = 5 1 0 4 1 <= k <= n <=5*10^4
p a r e n t [ 0 ] = = 1 parent[0] == -1 表示编号为 0 的节点是根节点。
对于所有的 0 < i < n 0 < = p a r e n t [ i ] < n 0 < i < n ,0 <= parent[i] < n 总成立
0 < = n o d e < n 0 <= node < n
至多查询 5 1 0 4 5*10^4

解题报告

因为是多次查询 getKthAncestor(int node, int k),如果每次执行查询,效率太低了,所以提前将结果存在二维数组中,之后直接 O(1) 的时间复杂度进行查询。
dp[i][j] 表示节点 i 的第 2 j 2^j 号祖父。
所以 d p [ i ] [ j ] = d p [ d p [ i ] [ j 1 ] ] [ j 1 ]        i f    d p [ i ] [ j 1 ] ! = 1 dp[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 个祖先

猜你喜欢

转载自blog.csdn.net/qq_27690765/article/details/106870007
今日推荐