1483. 树节点的第 K 个祖先

发布时间 2023-06-12 10:53:13作者: Tianyiya

给你一棵树,树上有 n 个节点,按从 0 到 n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。

树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。

实现 TreeAncestor 类:

TreeAncestor(int n, int[] parent) 对树和父数组中的节点数初始化对象。
getKthAncestor(int node, int k) 返回节点 node 的第 k 个祖先节点。如果不存在这样的祖先节点,返回 -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/kth-ancestor-of-a-tree-node
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Arrays;

class TreeAncestor {
    static final int LOG = (int) (Math.log(50000) / Math.log(2) + 1);
    int[][] ancestors;

    public TreeAncestor(int n, int[] parent) {
        ancestors = new int[n][LOG];
        for (int i = 0; i < n; i++) {
            Arrays.fill(ancestors[i], -1);
        }
        for (int i = 0; i < n; i++) {
            ancestors[i][0] = parent[i];
        }
        for (int j = 1; j < LOG; j++) {
            for (int i = 0; i < n; i++) {
                if (ancestors[i][j - 1] != -1) {
                    ancestors[i][j] = ancestors[ancestors[i][j - 1]][j - 1];
                }
            }
        }
    }

    public int getKthAncestor(int node, int k) {
        for (int i = 0; i < LOG && node != -1; i++) {
            if (((k >> i) & 1) != 0) {
                node = ancestors[node][i];
            }
        }
        return node;
    }
}