leetcode--树节点的第 K 个祖先

 题目是LeetCode第193场周赛的第四题,链接:1483. 树节点的第 K 个祖先。具体描述为:给你一棵树,树上有n个节点,按从0n-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 因为不存在满足要求的祖先节点

 这道题看起来不咋难,可以直接一个一个父节点往上找,每次查找的时间复杂度就是 O ( k ) O(k) O(k),但是最后还是会超时,这就意味着需要减少查询时间复杂度,那就只能往 O ( l o g k ) O(logk) O(logk)去了,而这就需要做一些初始化操作。

 具体做法其实还是类似于动态规划,我们用dp[i][j]代表距离节点j距离为2^i的父节点,那么假如我们要查找一个跟节点j距离为k的父节点,可以把k先写成k=2^x1+2^x2+...,那么就可以先查找距离为2^x1的父节点node=dp[x1][j],然后再继续找跟当前父节点距离为2^x2的父节点node=dp[x2][node]。反正一直这么下去就可以找到总距离为k的父节点。构建dp数组的时间复杂度为O(nlogn),每次查找的时间复杂度为O(logk)

 JAVA版代码如下:

class TreeAncestor {
    private int[][] dp;

    public TreeAncestor(int n, int[] parent) {
        // dp[i][j]: 距离节点j距离为2^i的节点
        int bits = (int)Math.ceil(Math.log(n * 1.0) / Math.log(2));
        dp = new int[bits][n];
        for (int j = 0; j < n; ++j) {
            dp[0][j] = parent[j];
        }
        for (int i = 1; i < bits; ++i) {
            for (int j = 0; j < n; ++j) {
                // 2^i = 2^(i-1) * 2^(i-1)
                dp[i][j] = dp[i - 1][j] == -1 ? -1 : dp[i - 1][dp[i - 1][j]];
            }
        }
    }
    
    public int getKthAncestor(int node, int k) {
        int i = 0;
        while (k > 0) {
            if (node < 0) {
                return -1;
            }
            if ((k & 1) == 1) {
                node = dp[i][node];
            }
            ++i;
            k >>>= 1;
        }
        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);
 */

 提交结果如下:

leetcode--树节点的第 K 个祖先_第1张图片

 Python版代码如下:

class TreeAncestor:

    def __init__(self, n: int, parent: List[int]):
        bits = math.ceil(math.log(n, 2))
        self.dp = [[0 for _ in range(n)] for _ in range(bits)]
        for j in range(n):
            self.dp[0][j] = parent[j]
        for i in range(1, bits):
            for j in range(n):
                self.dp[i][j] = -1 if self.dp[i - 1][j] == -1 else self.dp[i - 1][self.dp[i - 1][j]]

    def getKthAncestor(self, node: int, k: int) -> int:
        i = 0
        while k > 0:
            if node == -1:
                return -1
            if k % 2 == 1:
                node = self.dp[i][node]
            i += 1
            k >>= 1
        return node      


# Your TreeAncestor object will be instantiated and called as such:
# obj = TreeAncestor(n, parent)
# param_1 = obj.getKthAncestor(node,k)

 提交结果如下:

leetcode--树节点的第 K 个祖先_第2张图片

你可能感兴趣的:(LeetCode,数据结构,java,python,leetcode,算法)